public class Logger { private static ILog logger; static Logger() { if (logger == null) { var repository = LogManager.CreateRepository("NETCoreRepository"); //log4net从log4net.config文件中读取配置信息 XmlConfigurator.Configure(repository, new FileInfo("log4net.config")); logger = LogManager.GetLogger(repository.Name, "Logger"); } } public static void Info(string message, Exception exception = null) { if (exception == null) logger.Info(message); else logger.Info(message, exception); } public static void Warn(string message, Exception exception = null) { if (exception == null) logger.Warn(message); else logger.Warn(message, exception); } public static void Error(string message, Exception exception = null) { if (exception == null) logger.Error(message); else logger.Error(message, exception); } }
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="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender"> <file value="Log/" /> <appendToFile value="true" /> <rollingStyle value="Composite" /> <staticLogFileName value="false" /> <datePattern value="yyyyMMdd'.log'" /> <maxSizeRollBackups value="10" /> <maximumFileSize value="50MB" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%date [%thread] %-5level %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="RollingLogFileAppender" /> </root> </log4net> </configuration>
然后,在该调用的地方,直接调用
[Route("api/[controller]/[action]")] public class LogController:Controller { [HttpGet] public IActionResult Get(string x) { Logger.Info("info:" + x); Logger.Warn("warn:" + x); return Ok(x); } }
即可在console和file中显示
log4net查看地址:http://logging.apache.org/log4net/release/manual/configuration.html