working on it ...

Filters

Explore Public Snippets

Sort by

Found 89 snippets matching: log4net

    public by cghersi  4301  2  8  0

    A generic purpose Configuration Reader for .NET apps and web sites in C#

    This class can be extended to provide the capability to read the content of your configuration file, e.g. the web.config in web sites, the app.config in applications as well as a custom file for other purposes
    using System;
    using System.Configuration;
    using System.Web;
    using System.IO;
    using System.Xml.Linq;
    using System.Xml;
    using System.Collections;
    using System.Collections.Generic;
    using log4net;
    using log4net.Config;
    
    public abstract class ConfigReader
    {
        #region PROTECTED PARAMETERS
        /////////////////////////////////////////////////////////////////////////////////////////////////////
    
        protected string m_lastErrorMessage = string.Empty;
    
        protected XDocument m_customConfig = null;  //custom config XML file
        protected string m_name = string.Empty; //just an example of a string property to be read
        protected bool m_logWarnings = false; //just an example of a boolean property to be read
    
        protected string m_rootLocalPath;
            
        #endregion
        /////////////////////////////////////////////////////////////////////////////////////////////////////
    
    
        #region PUBLIC PROPERTIES
        /////////////////////////////////////////////////////////////////////////////////////////////////////
    
        public string LastError { get { return m_lastErrorMessage;  } }
        public string Name { get { return m_name; } }
    	public bool LogWarnings { get { return m_logWarnings; } }
      
        #endregion
        /////////////////////////////////////////////////////////////////////////////////////////////////////
    
    
        #region Constructors
    
        protected ConfigReader() 
        {
        }
    
        public virtual bool Initialize(string rootPath)
        {
            m_rootLocalPath = rootPath;
    
            //Load custom config file if it is available:
            LoadCustomConfigXMLFile();
    
            GetSetting("Server", ref m_name);
            if ( !GetSetting("LogWarning", ref m_logWarnings) )
                m_logWarnings = false;
    
            // Log4Net initialization:
            FileInfo log4netFile = new FileInfo(string.Format("{0}\\log4net.config", rootPath));
            if (log4netFile.Exists)
                XmlConfigurator.Configure(log4netFile);
            else
                XmlConfigurator.Configure();
            ILog log = log4net.LogManager.GetLogger(this.GetType());
    
            log.Info("Log4net correctly started");
    
            return true;
        }
    
        #endregion
    
        /////////////////////////////////////////////////////////////////////////////////////////////////////
    
        #region Public API
    
        public string GetSetting(string propName)
        {
            try
            {
                if (ConfigurationManager.AppSettings.Get(propName) != null)
                    return ConfigurationManager.AppSettings.Get(propName).ToString();
                else if (m_customConfig != null)
                {
                    string res = string.Empty;
                    m_customConfig.Root.ParseNode(propName, ref res);
                    return res;
                }
                else
                    return string.Empty;
            }
            catch { }
    
            return string.Empty;
        }
    
        protected bool GetSetting(string propName, ref string property)
        {
            try
            {
                if (ConfigurationManager.AppSettings.Get(propName) != null)
                    property = ConfigurationManager.AppSettings.Get(propName).ToString();
                else if (m_customConfig != null)
                    m_customConfig.Root.ParseNode(propName, ref property);
                else
                    return false;
                return true;
            }
            catch 
            {
                return false;
            }
        }
    
        protected bool GetSetting(string propName, ref bool property)
        {
            string prop = string.Empty;
            if ( GetSetting(propName, ref prop) )
                return bool.TryParse(prop, out property);
            else
                return false;
        }
    
        protected bool GetSetting(string propName, ref int property)
        {
            string prop = string.Empty;
            if (GetSetting(propName, ref prop))
                return int.TryParse(prop, out property);
            else
                return false;
        }
    
        protected bool GetSetting<T>(string propName, ref T property)
        {
            string prop = string.Empty;
            if (GetSetting(propName, ref prop))
            {
                try
                {
                    property = (T)Enum.Parse(typeof(T), prop, true);
                }
                catch
                {
                    return false;
                }
                return true;
            }
            else
                return false;
        }
        #endregion
    
        /////////////////////////////////////////////////////////////////////////////////////////////////////
    
        #region Protected internal utility functions
    
        /// <summary>
        /// Load in memory the xml describing the configuration, if any
        /// </summary>
        /// ------------------------------------------------------------------------------------------
        protected bool LoadCustomConfigXMLFile()
        {
            string path = string.Format("{0}\\mycfg.config", m_rootLocalPath);
            try
            {
                m_customConfig = XDocument.Load(path);
            }
            catch
            {
                // error loading document: Not found
                m_customConfig = null;
                return false;
            }
    
            return true;
        }
    
        #endregion
        /////////////////////////////////////////////////////////////////////////////////////////////////////
    }
    

    public by cgarlos  2934  6  5  0

    Generic way to declare log4net variable

    This is a way to declare a static log4net variable that doesn't require the actual name of the current class to be typed, so it can be copy&pasted in each class you need!
    private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

    public by cherso  2092  2  7  1

    Declare log4net static variable in all the classes

    this is the most effective way to declare just only once a log4net static variable for an entire class. You may also provide the same variable in a parent class, not as static, just to declare it once in your code
    private static readonly log4net.ILog log = 
      log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
    

    public by snip2code  6131  9  8  0

    Send an HTTP Request in C#

    This is a core method to send an HTTP Request in C#. It is able to store and re-use the set of cookies used in the past calls. It makes use of log4net library to log information regarding the process.
    private CookieContainer m_cookies = new CookieContainer();
    
    public string SendRequest(string serviceUrl, string data, bool isPost)
    {
        HttpWebRequest webRequest = null;
        log.DebugFormat("Creating request {0}", serviceUrl);
        try
        {
            webRequest = WebRequest.Create(serviceUrl) as HttpWebRequest;
        }
        catch (UriFormatException ufe)
        {
            log.ErrorFormat("Cannot connect to {0} due to {1} ", serviceUrl, ufe.Message);
            return string.Empty;
        }
    
        if (isPost)
        {
            webRequest.Method = "POST";
            webRequest.ContentType = "application/x-www-form-urlencoded";
        }
    
        webRequest.Accept = "application/json";
        webRequest.ServicePoint.ConnectionLimit = 10;
        webRequest.ServicePoint.Expect100Continue = false; //this would prevent waiting infinite time for this HTTP 100 CONTINUE (unuseful)
        webRequest.CookieContainer = m_cookies;             // send out cookie along with a request for the protected page
        //Add here some custom headers, if needed:
        //webRequest.Headers.Add("MyCustomHeader", "Header value");
        if (isPost && (data != null))
            webRequest.ContentLength = data.Length;
    
        StreamReader responseReader = null;
        string responseData = string.Empty;
        WebResponse webResp = null;
        try
        {
            if (isPost)
            {
                log.DebugFormat("Posting request {0}", serviceUrl);
    
                // write the form values into the request message
                StreamWriter requestWriter = new StreamWriter(webRequest.GetRequestStream());
                requestWriter.Write(data);
                requestWriter.Flush();
                requestWriter.Close();
                requestWriter.Dispose();
            }
    
            log.DebugFormat("Number of active connections: {0}", webRequest.ServicePoint.CurrentConnections);
            log.DebugFormat("Getting web response for request {0}", serviceUrl);
            webResp = webRequest.GetResponse();
            log.DebugFormat("Getting web response stream for request {0}", serviceUrl);
            Stream webStream = webResp.GetResponseStream();
            log.DebugFormat("Creating reader for request {0}", serviceUrl);
            responseReader = new StreamReader(webStream);
    
            //read the response:
            log.DebugFormat("Reading response for request {0}", serviceUrl);
            responseData = responseReader.ReadToEnd();
        }
        catch (WebException wex)
        {
            log.ErrorFormat("Cannot connect to {0} due to {1} ", serviceUrl, wex.Message);
            if ((webRequest != null) && (webRequest.ServicePoint != null))
                log.ErrorFormat("Number of active connections: {0}", webRequest.ServicePoint.CurrentConnections);
            return string.Empty;
        }
        catch (IOException ioex)
        {
            log.ErrorFormat("Cannot read data from to {0} due to {1} ", serviceUrl, ioex.Message);
            if ((webRequest != null) && (webRequest.ServicePoint != null))
                log.ErrorFormat("Number of active connections: {0}", webRequest.ServicePoint.CurrentConnections);
            return string.Empty;
        }
        finally
        {
            if (responseReader != null)
            {
                responseReader.Close();
                responseReader.Dispose();
            }
            if (webResp != null)
                webResp.Close();
            webRequest = null;
        }
    
        log.DebugFormat("Response read for request {0}", serviceUrl);
    
        return responseData;
    }
    

    public by msdn  1276  0  6  0

    CreateLogger: Create a new logger, in this case there is only type - log4net

    Create a new logger, in this case there is only type - log4net
    using BulkLoader.Types;
    
    /// <summary>
    /// Create a new logger, in this case there is only type - log4net
    /// </summary>
    /// <param name="loggerName"></param>
    /// <returns></returns>
    public static IBulkLoaderLogger CreateLogger(string loggerName)
    {
        return new Log4NetLogger(loggerName);
    }

    external by cesar-carrasco  137514  2  4  0

    log4net UDP Appender to send signals to Graphite server

    log4net UDP Appender to send signals to Graphite server: log4net.config.xml
    XML
      <appender name="GraphiteUdpAppender" type="log4net.Appender.UdpAppender">
        <remoteAddress value="graphiteserver.somewhere.com"/>
        <remotePort value="8125"/>
        <layout type="log4net.Layout.PatternLayout">
          <IgnoresException value="False"/>
          <conversionPattern value="%property{log4net:HostName}.log4net.%level:1|kv\n"/>
        </layout>
      </appender>
      
      <!-- Remember to add the appender to the root
        <root>
    	...
        <appender-ref ref="GraphiteUdpAppender" />
      </root>
      -->
      
    
    

    external by Rob Thijssen  217  0  3  0

    Allow log4net to create eventlog appenders under the user account specified by $username

    Allow log4net to create eventlog appenders under the user account specified by $username: grant-eventlogaccess.ps1
    param (
      [string] $username = "$env:USERDOMAIN\$env:USERNAME"
    )
    
    function GrantAccess ($principle, $log, $access) {
      $path = ('HKLM:\SYSTEM\CurrentControlSet\services\eventlog\{0}' -f $log)
      if (Test-Path $path) {
        Write-Host ('Granting {0} on {1} to {2}' -f $access, $path, $principle) -ForegroundColor Yellow
        Get-Acl $path | Format-List
        $acl = Get-Acl $path
        $rule = New-Object System.Security.AccessControl.RegistryAccessRule($principle, @($access), 'Allow')
        $acl.AddAccessRule($rule)
        Set-Acl $path $acl
        Write-Host ('Granted {0} on {1} to {2}' -f $access, $path, $principle) -ForegroundColor DarkGreen
        Get-Acl $path | Format-List
      } else {
        Write-Error "Cannot acesss $path"
      }
    }
    
    GrantAccess $username 'Application' 'ReadKey, WriteKey'
    GrantAccess $username 'Security' 'ReadKey'
    
    
    

    external by haasey  365  0  3  0

    Log4Net.config separate file for just Log4Net configuration

    Log4Net.config separate file for just Log4Net configuration: gistfile1.txt
    <?xml version="1.0" encoding="utf-8"?>
    <log4net>
      <appender name="EventLogAppender" type="log4net.Appender.EventLogAppender" >
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
        </layout>
      </appender>
      <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
        <file value="..\Logs\CurrentLog.txt" />
        <appendToFile value="true" />
    
        <rollingStyle value="Size" />
        <maxSizeRollBackups value="10" />
        <maximumFileSize value="10000" />
        <staticLogFileName value="true" />
        <!-- Alternatively, roll on date -->
        <!-- <rollingStyle value="Date" /> -->
        <!-- <datePattern value="yyyyMMdd" /> -->
        <filter type="log4net.Filter.LevelRangeFilter">
          <acceptOnMatch value="true" />
          <levelMin value="INFO" />
          <levelMax value="FATAL" />
        </filter>
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%-5level %date [%thread] %-22.22c{1} - %m%n" />
        </layout>
      </appender>   
      <appender name="SmtpAppender" type="log4net.Appender.SmtpAppender">
        <to value="you@yourcompany.com" />
        <from value="YourApplicationName@cartech.com" />
        <subject value="Error YourAppliction [Production]" />
        <smtpHost value="smtp.yourcompany.com" />
        <bufferSize value="512" />
        <lossy value="true" />
        <evaluator type="log4net.Core.LevelEvaluator">
          <threshold value="Error"/>    
        </evaluator>
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%newline%date [%thread] %-5level %logger [%property{NDC}] - %message%newline%newline%newline" />
        </layout>
      </appender>  
      <root>
        <level value="DEBUG" />
        <appender-ref ref="EventLogAppender" />
        <appender-ref ref="RollingFileAppender" />
        <appender-ref ref="SmtpAppender" />
      </root>
    </log4net>
    
    

    external by kzelda  126  0  2  0

    Résolution du problème log4net x64 ....

    Résolution du problème log4net x64 ....: subst.bat
    -- Créer un lecteur virtuel t:)
    subst t: C:\Windows\assembly
    
    del t:\GAC_64\log4net\1.2.10.0__692fbea5521e1304\log4net.dll
    
    -- Supprimer le lecteur créé
    subst t: /d
    
    

    external by pbering  4245  37  4  0

    Log4Net Appender that submits errors to NewRelic

    Log4Net Appender that submits errors to NewRelic : gistfile1.cs
    using System;
    using System.Collections.Generic;
    using log4net.Appender;
    using log4net.spi;
    using Sitecore.Data.Items;
    
    namespace SitecoreDiagnostics.NewRelic
    {
        public class Log4NetErrorAppender : AppenderSkeleton
        {
            protected override void Append(LoggingEvent loggingEvent)
            {
                if (!Configuration.NewRelicEnabled)
                {
                    return;
                }
    
                if (loggingEvent.Level < Level.ERROR)
                {
                    return;
                }
    
                // Skip exceptions
                var isException = !string.IsNullOrEmpty(loggingEvent.GetExceptionStrRep());
    
                if (isException)
                {
                    return;
                }
    
                IDictionary<string, string> parameters = new Dictionary<string, string>();
    
                parameters.Add("Level", loggingEvent.Level.ToString());
                parameters.Add("LoggerName", loggingEvent.LoggerName);
                parameters.Add("ThreadName", loggingEvent.ThreadName);
                parameters.Add("Machine", Environment.MachineName);
                parameters.Add("Identity", loggingEvent.Identity);
    
                string siteName;
    
                if (SitecoreContextHelper.TryGetSiteName(out siteName))
                {
                    parameters.Add("Site", siteName);
                }
    
                string languageName;
    
                if (SitecoreContextHelper.TryGetLanguageName(out languageName))
                {
                    parameters.Add("Language", languageName);
                }
    
                string databaseName;
    
                if (SitecoreContextHelper.TryGetDatabaseName(out databaseName))
                {
                    parameters.Add("Database", databaseName);
                }
    
                string deviceName;
    
                if (SitecoreContextHelper.TryGetDeviceName(out deviceName))
                {
                    parameters.Add("Device", deviceName);
                }
    
                Item item;
    
                if (SitecoreContextHelper.TryGetItem(out item))
                {
                    parameters.Add("ItemPath", item.Paths.FullPath);
    
                    global::NewRelic.Api.Agent.NewRelic.SetTransactionName("Custom", TransactionNaming.GetName(item, deviceName));
                }
    
                global::NewRelic.Api.Agent.NewRelic.NoticeError(loggingEvent.MessageObject.ToString(), parameters);
            }
        }
    }
    
    
    • Public Snippets
    • Channels Snippets