Log4Net (edit)
http://rion.io/2017/11/18/knowing-when-to-reflect-with-caller-info-attributes/
Trace Log
using System.Runtime.CompilerServices;
...
public static class Helpers
{
public static string GetCallerName([CallerMemberName] string caller = null)
{
return caller;
}
}
Solution 1: Without namespace
using System.Diagnostics;
...
Logger.Log.Info(string.Format("{0} called at {1}",
new System.Diagnostics.StackFrame(1, true).GetMethod(),
System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));
Solution 2: Without namespace (BEST SOLUTION)
Logger.Log.Info(string.Format("{0} called at {2}"
, Helpers.GetCallerName()
, System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));
Solution 3: With namespace
using System.Reflection;
...
Logger.Log.Info(string.Format("{0}.{1} called at {2}"
, System.Reflection.MethodBase.GetCurrentMethod().ReflectedType.Namespace
, Helpers.GetCallerName()
, System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));
Web.config
<?xml version="1.0" encoding="utf-8"?> <configuration> <configSections> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" /> ...
<log4net> <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender"> <file value="Logs\\WebApplication1.log" /> <appendToFile value="true" /> <encoding value="UTF-8" /> <rollingStyle value="Size" /> <maxSizeRollBackups value="5" /> <maximumFileSize value="5MB" /> <staticLogFileName value="true" /> <lockingModel type="log4net.Appender.FileAppender+MinimalLock" /> <layout type="log4net.Layout.PatternLayout"> <param name="ConversionPattern" value="%date{dd-MM-yy HH:mm:ss} %-5level %message%newline" /> </layout> </appender> <appender name="TraceAppender" type="log4net.Appender.TraceAppender"> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%date{dd-MM-yy HH:mm:ss} %-5level %message%newline" /> </layout> </appender> <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender"> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%-5level %message%newline" /> </layout> </appender> <root> <level value="All" /> <appender-ref ref="RollingFileAppender" /> <appender-ref ref="TraceAppender" /> <appender-ref ref="ConsoleAppender" /> </root> </log4net> </configuration>
Logger.cs
public class Logger { private static readonly ILog log = LogManager.GetLogger(typeof(Logger)); public static ILog Log { get { return Logger.log; } } }
AssemblyInfo.cs
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
Global.asax.cs
public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { log4net.Config.XmlConfigurator.Configure();