.net core 使用 log4net
.net core 使用 log4net
1 新建 .net 6 webapi 项目
2 安装nuget包 log4net
添加引用
using System.IO;
using log4net;
using log4net.Config;
using log4net.Repository;
3 新建工具类 Log4NetUtil
public class Log4NetUtil { private static ILoggerRepository _repository; private static ILog _log; private static ILog log { get { if (_log == null) { Configure(); } return _log; } } public static void Configure(string repositoryName = "NETCoreRepository", string configFile = "log4net.config") { _repository = LogManager.CreateRepository(repositoryName); XmlConfigurator.Configure(_repository, new FileInfo(configFile)); _log = LogManager.GetLogger(repositoryName, ""); } public static void Info(string msg) { log.Info(msg); } public static void Warn(string msg) { log.Warn(msg); } public static void Error(string msg) { log.Error(msg); } }
4 添加 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 %newline%message%newline%newline" /> </appender> <appender name="FileAppender" type="log4net.Appender.FileAppender"> <file value="log-file.log" /> <appendToFile value="true" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%date [%thread] %-5level %newline%message%newline%newline" /> </layout> </appender> <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender"> <file value="log4file/" /> <appendToFile value="true" /> <rollingStyle value="Composite" /> <staticLogFileName value="false" /> <datePattern value="yyyyMMdd'.log'" /> <maxSizeRollBackups value="10" /> <maximumFileSize value="10MB" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%date [%thread] %-5level %newline%message%newline%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="FileAppender" /> <appender-ref ref="RollingLogFileAppender" /> </root> </log4net> </configuration>
设置 log4net.config 文件属性,始终复制
写日志代码
public IEnumerable<WeatherForecast> Get() { Log4NetUtil.Info("这是 info"); Log4NetUtil.Warn("这是 Warn"); Log4NetUtil.Error("这是 Error"); return Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateTime.Now.AddDays(index), TemperatureC = Random.Shared.Next(-20, 55), Summary = Summaries[Random.Shared.Next(Summaries.Length)] }) .ToArray(); }
本文引用:https://www.cnblogs.com/tomorrow0/p/16320229.html