1, XmlConfigurator
创建添加一个Tracer project,引用nuget上最新的log4net
在Tracer里新增一个AppLog类:
public static class AppLog { private static ILog log; static AppLog() { string path = System.IO.Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "log4net.config"); XmlConfigurator.ConfigureAndWatch(new FileInfo(path)); log = LogManager.GetLogger(typeof(AppLog)); WriteHeaderInfo(); } public static void Debug(object message) { log.Debug(message); } public static void Debug(string format, params object[] args) { log.DebugFormat(format, args); } public static void Info(object message) { log.Info(message); } public static void Info(string format, params object[] args) { log.InfoFormat(format, args); } public static void Warn(object message) { log.Warn(message); } public static void Warn(object message, Exception exception) { log.Warn(message, exception); } public static void WarnFormatted(string format, params object[] args) { log.WarnFormat(format, args); } public static void Error(object message) { log.Error(message); } public static void Error(object message, Exception exception) { log.Error(message, exception); } public static void ErrorFormatted(string format, params object[] args) { log.ErrorFormat(format, args); } public static void Fatal(object message) { log.Fatal(message); } public static void Fatal(object message, Exception exception) { log.Fatal(message, exception); } public static void FatalFormatted(string format, params object[] args) { log.FatalFormat(format, args); } /// <summary> /// Write the logging header, e.g. some system informations /// </summary> /// <returns></returns> private static void WriteHeaderInfo() { System.Reflection.Assembly myAssembly = System.Reflection.Assembly.GetExecutingAssembly(); System.Version appVersion = myAssembly.GetName().Version; string strDomainName = string.Empty; string strUserName = string.Empty; string OSType = Is64BitWindowsOS() ? "64-bit" : "32-bit"; FileInfo file = new FileInfo(myAssembly.Location); string createDate = file.CreationTime.ToString("yyyy-MM-dd HH:mm:ss"); log.Info("=============================================================================================================="); log.Info(string.Empty); log.Info(string.Format(" [Version: {0}] Logging started at {1}", appVersion.ToString(), System.DateTime.Now.ToString())); log.Info(string.Empty); log.Info(string.Format(" OS Version: {0}({1}) CLR Version: {2}", System.Environment.OSVersion.ToString(), OSType, System.Environment.Version.ToString())); log.Info(string.Format(" Language: {0} UI Language: {1}", System.Threading.Thread.CurrentThread.CurrentCulture.DisplayName, System.Threading.Thread.CurrentThread.CurrentUICulture.DisplayName)); log.Info(string.Format(" User Domain: {0} Username(Local Session): {1}", System.Environment.UserDomainName, System.Environment.UserName)); log.Info(string.Format(" User Domain: {0} Username(Network Session): {1}", strDomainName, strUserName)); log.Info(string.Format(" Build Created Time: {0}", createDate)); log.Info(string.Empty); log.Info("=============================================================================================================="); log.Info(string.Empty); } private static bool Is64BitWindowsOS() { bool is64Bit = false; try { string cpuType = System.Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE"); string originalCpuTypeOr = System.Environment.GetEnvironmentVariable("PROCESSOR_ARCHITEW6432"); if (string.Compare(cpuType, "amd64", true) == 0 || string.Compare(originalCpuTypeOr, "amd64", true) == 0) { is64Bit = true; } else { is64Bit = false; } } catch (System.Security.SecurityException e) { System.Diagnostics.Debug.Fail("Cannot detect the process bitness " + e.ToString()); } catch (Exception ex) { System.Diagnostics.Debug.Fail("Cannot detect the process bitness " + ex.ToString()); } return is64Bit; } }
在Tracer里创建一个log4net.config文件,并且确定这个文件在编译的时候会复制到对应文件夹
<?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="log4net" type="System.Configuration.IgnoreSectionHandler"/> </configSections> <log4net> <!--配置在root注册的appender-ref具体属性--> <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender"> <!--日志文件名开头--> <file value="Log"/> <!--是否追加到文件--> <appendToFile value="true"/> <!--混合使用日期和文件大小变换日志文件名--> <rollingStyle value="Composite"/> <!--日期的格式--> <datePattern value="yyyyMMdd".txt""/> <!--设置无限备份=-1 ,最大备份数为1000--> <maxSizeRollBackups value="500"/> <!--最大文件大小,可以使用"KB", "MB" 或 "GB"为 MaxFileSize 作为后缀限定大小。默认的文件大小是10MB--> <maximumFileSize value="5MB"/> <staticLogFileName value="false"/> <!--日志布局--> <layout type="log4net.Layout.PatternLayout"> <!--<conversionPattern value="%date [%thread] %-5level %logger -> %message%newline"/>--> <conversionPattern value="%date [%thread] %-5level -> %message%newline"/> </layout> </appender> <root> <!--定义Level级别,若没定义,默认为Debug--> <level value="All"/> <!--定义日志对象使用的appender,通过appeder-ref来注册--> <appender-ref ref="RollingLogFileAppender"/> </root> </log4net> </configuration>
这样,当其他app想写log,只需要调用AppLog的相关静态方法。
Tracer.AppLog.Debug("User calls method...Interval:{0}ms", Interval);
Tracer.AppLog.Debug("Start!");
2, BasicConfigurator
log4net也支持不用config文件的方式
比如,在上面的例子,我们可以不创建log4net.config文件,并且将AppLog的静态创建方法改写如下:
static AppLog() { PatternLayout layout = new PatternLayout("%date{MMM/dd/yyyy HH:mm:ss,fff} [%thread] %-5level %logger %ndc – %message%newline"); LevelMatchFilter filter = new LevelMatchFilter(); filter.LevelToMatch = Level.All; filter.ActivateOptions(); RollingFileAppender appender = new RollingFileAppender(); appender.File = Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "common.log"); appender.ImmediateFlush = true; appender.AppendToFile = true; appender.RollingStyle = RollingFileAppender.RollingMode.Date; appender.DatePattern = "-yyyy-MM-dd"; appender.LockingModel = new FileAppender.MinimalLock(); appender.Name = string.Format("{0}Appender", "AppLog"); appender.AddFilter(filter); appender.Layout = layout; appender.ActivateOptions(); string repositoryName = string.Format("{0}Repository", "AppLog"); ILoggerRepository repository = LoggerManager.CreateRepository(repositoryName); string loggerName = string.Format("{0}Logger", "AppLog"); BasicConfigurator.Configure(repository, appender); log = LogManager.GetLogger(repositoryName, loggerName);//这是重点 WriteHeaderInfo(); }
参考文章:
How to programmatically create log instance by Log4Net library