public class YFLog { private static log4net.ILog logger = null; public static void logInfo(string logstr) { Console.WriteLine(logstr); if(initLog4net()) logger.Info(logstr); } public static void logInfo(string format, params object[] args) { Console.WriteLine(format, args); if (initLog4net()) logger.InfoFormat(format, args); } public static void logError(string logstr) { Console.WriteLine(logstr); if (initLog4net()) logger.Error(logstr); } public static void logError(string format, params object[] args) { Console.WriteLine(format, args); if (initLog4net()) logger.ErrorFormat(format, args); } private static object objlock = new object();//初始化log用的锁 private static bool initLog4net() { if (logger != null) return true; lock (objlock) { if (logger == null) { ILoggerRepository repository = LogManager.CreateRepository("NETCoreRepository"); XmlConfigurator.Configure(repository, new FileInfo("log4net.config")); logger = LogManager.GetLogger(repository.Name, "NETCorelog4net"); return true; } } return false; } }
log4net.config
<?xml version="1.0" encoding="utf-8" ?> <configuration> <!-- This section contains the log4net configuration settings --> <log4net> <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender"> <layout type="log4net.Layout.PatternLayout" value="%date [%thread] %-5level %logger - %message%newline" /> </appender> <appender name="errorAppender" type="log4net.Appender.RollingFileAppender"> <file value="Logs/" /> <appendToFile value="true" /> <rollingStyle value="Composite" /> <staticLogFileName value="false" /> <datePattern value="error-yyyyMMdd'.log'" /> <maxSizeRollBackups value="10" /> <maximumFileSize value="1MB" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" /> </layout> </appender> <appender name="infoAppender" type="log4net.Appender.RollingFileAppender"> <file value="Logs/" /> <appendToFile value="true" /> <rollingStyle value="Composite" /> <staticLogFileName value="false" /> <datePattern value="yyyyMMdd'.log'" /> <maxSizeRollBackups value="10" /> <maximumFileSize value="1MB" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" /> </layout> </appender> <!-- Setup the root category, add the appenders and set the default level --> <root> <level value="ALL" /> <appender-ref ref="ConsoleAppender" /> <appender-ref ref="errorAppender" /> <appender-ref ref="infoAppender" /> </root> </log4net> </configuration>