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); } ////// Write the logging header, e.g. some system informations /// ///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("\t[Version: {0}] Logging started at {1}", appVersion.ToString(), System.DateTime.Now.ToString())); log.Info(string.Empty); log.Info(string.Format("\tOS Version: {0}({1})\tCLR Version: {2}", System.Environment.OSVersion.ToString(), OSType, System.Environment.Version.ToString())); log.Info(string.Format("\tLanguage: {0}\tUI Language: {1}", System.Threading.Thread.CurrentThread.CurrentCulture.DisplayName, System.Threading.Thread.CurrentThread.CurrentUICulture.DisplayName)); log.Info(string.Format("\tUser Domain: {0}\tUsername(Local Session): {1}", System.Environment.UserDomainName, System.Environment.UserName)); log.Info(string.Format("\tUser Domain: {0}\tUsername(Network Session): {1}", strDomainName, strUserName)); log.Info(string.Format("\tBuild 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\n" + e.ToString()); } catch (Exception ex) { System.Diagnostics.Debug.Fail("Cannot detect the process bitness\n" + ex.ToString()); } return is64Bit; } }
在Tracer里创建一个log4net.config文件,并且确定这个文件在编译的时候会复制到对应文件夹
这样,当其他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(); }
参考文章: