Thursday 27 November 2014

Change the log file path in Microsoft.Practices.EnterpriseLibrary.Logging.Configuration

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using Microsoft.Practices.EnterpriseLibrary.Logging;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Security.Cryptography;
using System.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Logging.Configuration;

namespace TestInterface
{
    internal class Program
    {
        internal static int ExitCode = 0;
        static void Main(string[] args)
        {
            string logFilePath = Environment.GetEnvironmentVariable("LogFile", EnvironmentVariableTarget.Process);
            SetupRuntimeConfiguration(logFilePath);

            ProcessData();
            Environment.Exit(ExitCode);
        }

        public static void SetupRuntimeConfiguration(string logFilePath)
        {
            string loggingConfigurationSectionName = "loggingConfiguration";

            //Create the Configuration object
            //System.Configuration.ExeConfigurationFileMap configFileMap = new System.Configuration.ExeConfigurationFileMap();

            //The ExeConfigFilename is the absolute path of the config file
            // configFileMap.ExeConfigFilename = enterpriseLibraryConfig;

            System.Configuration.Configuration entLibConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);


            //Open our configuration file instead of the default app configuration
            //Configuration entLibConfig = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, System.Configuration.ConfigurationUserLevel.None);

            //Check if the configuration file exist
            if (!entLibConfig.HasFile)
            {
                return;
            }

            //Get the logging ConfigurationSection
            LoggingSettings settings = (LoggingSettings)entLibConfig.GetSection(loggingConfigurationSectionName);

            //Dynamically set the location of the trace listener to a directory
            //that allows Enterprise Library to read and write.
            //Handle the trace listeners that has a fileName property.
            foreach (TraceListenerData traceListernData in settings.TraceListeners)
            {
                FlatFileTraceListenerData flatFileTraceListener = traceListernData as FlatFileTraceListenerData;
                XmlTraceListenerData xmlTraceListener = traceListernData as XmlTraceListenerData;
                RollingFlatFileTraceListenerData rollingFileTraceListener =
                    traceListernData as RollingFlatFileTraceListenerData;

                if (flatFileTraceListener != null)
                {
                    flatFileTraceListener.FileName = logFilePath;
                }
                if (rollingFileTraceListener != null)
                {
                    rollingFileTraceListener.FileName = logFilePath;
                }
                if (xmlTraceListener != null)
                {
                    xmlTraceListener.FileName = logFilePath;
                }
            }
            //Make sure the configuration file is in a directory where the user have write permission.
            entLibConfig.Save();
        }      

        static void ProcessData()
        {
            try
            {
                Logger.Write(new LogEntry { Title = "ProcessData", Severity = TraceEventType.Verbose, TimeStamp = DateTime.Now, Message = "Message: SAP Data Refresh Started" });             


                Logger.Write(new LogEntry { Title = "ProcessData", Severity = TraceEventType.Verbose, TimeStamp = DateTime.Now, Message = "Message: SAP Data Refresh Completed" });
            }
            catch (Exception ex)
            {
                // if any exception write to the log file
                Logger.Write(new LogEntry { Title = "ProcessSAPDataRefresh:", Severity = TraceEventType.Error, TimeStamp = DateTime.Now, Message = "Message:" + ex.Message + " Stack Trace:" + ex.StackTrace });
                ExitCode = 20000;
            }
        }
   }
}

app.config:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
      <section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=5.0.505.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
      <section name="loggingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.505.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
    </configSections>
     <appSettings>
        </appSettings>
    <loggingConfiguration name="" tracingEnabled="true" defaultCategory="General">
      <listeners>
        <add name="Rolling Flat File Trace Listener" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.RollingFlatFileTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.505.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
            listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.RollingFlatFileTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.505.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
            fileName="C:\log1.log" formatter="Text Formatter"
            rollFileExistsBehavior="Increment" rollInterval="Day" />
      </listeners>
      <formatters>
        <add type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.505.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
            template="Timestamp: {timestamp}{newline}&#xA;Message: {message}{newline}&#xA;Category: {category}{newline}&#xA;Priority: {priority}{newline}&#xA;EventId: {eventid}{newline}&#xA;Severity: {severity}{newline}&#xA;Title:{title}{newline}&#xA;Machine: {localMachine}{newline}&#xA;App Domain: {localAppDomain}{newline}&#xA;ProcessId: {localProcessId}{newline}&#xA;Process Name: {localProcessName}{newline}&#xA;Thread Name: {threadName}{newline}&#xA;Win32 ThreadId:{win32ThreadId}{newline}&#xA;Extended Properties: {dictionary({key} - {value}{newline})}"
            name="Text Formatter" />
      </formatters>
      <categorySources>
        <add switchValue="All" name="General">
          <listeners>
            <add name="Rolling Flat File Trace Listener" />
          </listeners>
        </add>
      </categorySources>
      <specialSources>
        <allEvents switchValue="All" name="All Events" />
        <notProcessed switchValue="All" name="Unprocessed Category" />
        <errors switchValue="All" name="Logging Errors &amp; Warnings">
          <listeners>
            <add name="Rolling Flat File Trace Listener" />
          </listeners>
        </errors>
      </specialSources>
    </loggingConfiguration>
    <system.serviceModel>
        <bindings>
            <basicHttpBinding>
                <binding name="YAX_READ_TABLEBinding" closeTimeout="00:01:00"
                    openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
                    allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
                    maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
                    messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
                    useDefaultWebProxy="true">
                    <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
                        maxBytesPerRead="4096" maxNameTableCharCount="16384" />
                    <security mode="None">
                        <transport clientCredentialType="None" proxyCredentialType="None"
                            realm="" />
                        <message clientCredentialType="UserName" algorithmSuite="Default" />
                    </security>
                </binding>
            </basicHttpBinding>
            <customBinding>
              <binding name="Config1" closeTimeout="00:01:00" openTimeout="00:01:00"
                receiveTimeout="00:10:00" sendTimeout="00:01:00">
                <textMessageEncoding maxReadPoolSize="64" maxWritePoolSize="16"
                  messageVersion="Soap11" writeEncoding="utf-8">
                  <readerQuotas maxDepth="32" maxStringContentLength="2147483647" maxArrayLength="2147483647"
                    maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
                </textMessageEncoding>
                <httpTransport maxReceivedMessageSize="2147483647" authenticationScheme="Basic"
                  bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
                  keepAliveEnabled="false" proxyAuthenticationScheme="Basic" realm=""
                  useDefaultWebProxy="true" />
              </binding>
            </customBinding>
        </bindings>
        <client>
            <endpoint address="http://../sap/bc/soap/rfc" binding="customBinding"
                bindingConfiguration="Config1" contract="YaxReadTable.YAX_READ_TABLEPortType"
                name="YAX_READ_TABLEPortType" />
          <!--<endpoint address="http://.../sap/bc/soap/rfc" binding="customBinding"
              bindingConfiguration="Config1" contract="YaxReadTable.YAX_READ_TABLEPortType"
              name="YAX_READ_TABLEPortType" />-->
        </client>
    </system.serviceModel>
</configuration>

No comments:

Post a Comment