.NetCore WebApi 添加 Log4Net


一 、配置

1.vs2019 創建一個.net core web程序,選擇webapi

2.項目中添加一個配置文件:添加--新建項--XML文件,命名為log4net.config

我使用的是log4net的RollingLogFileAppender,他的好處是按天記錄日志,一般日志記錄會選擇30天

<configuration>
<!-- This section contains the log4net configuration settings -->
<log4net>
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<!--文件位置-->
<file value="LogFile/" />
<!--附加文件-->
<appendToFile value="true" />
<!--按天記錄-->
<rollingStyle value="Date" />
<datePattern value="yyyyMMdd'.log'" />
<staticLogFileName value="false" />
<!--只記錄31天-->
<MaxSizeRollBackups value="31" />
<!--輸出格式-->
<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="RollingLogFileAppender" />
</root>

</log4net>
</configuration>

更多選項參考:http://logging.apache.org/log4net/release/config-examples.html

3.startup配置

public static ILoggerRepository repository { get; set; }

public Startup(IConfiguration configuration)
{

Configuration = configuration;

repository = LogManager.CreateRepository("NETCoreRepository");
XmlConfigurator.Configure(repository, new FileInfo("log4net.config"));
}

 

二、應用

public class ValuesController : ControllerBase
{

private log4net.ILog log = log4net.LogManager.GetLogger(Startup.repository.Name, typeof(ValuesController));

public ActionResult<string> Get(int id)
{
log.Info($"ValuesController-Get id:{id}");
return "value";
}

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM