环境
需要安装NuGet包,明细如下:
- log4net
- Microsoft.Extensions.Logging.Log4Net.AspNetCore
配置文件
文件名称 log4net.config
,默认可以放在与启动类Program.cs
同级目录下
xml
<?xml version="1.0" encoding="utf-8" ?>
<log4net>
<!-- Define the appender for info level -->
<appender name="InfoAppender" type="log4net.Appender.RollingFileAppender">
<file value="./LOG/info/" />
<appendToFile value="true" />
<rollingStyle value="Date" />
<datePattern value="'info.'yyyy-MM-dd'.log'" />
<staticLogFileName value="false" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
</layout>
<!-- Define a filter to only accept info level -->
<filter type="log4net.Filter.LevelRangeFilter">
<levelMin value="INFO" />
<levelMax value="INFO" />
</filter>
</appender>
<!-- Define the appender for error level -->
<appender name="ErrorAppender" type="log4net.Appender.RollingFileAppender">
<file value="./LOG/error/" />
<appendToFile value="true" />
<rollingStyle value="Date" />
<datePattern value="'error.'yyyy-MM-dd'.log'" />
<staticLogFileName value="false" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger - %message%newline%exception%newline" />
</layout>
<!-- Define a filter to only accept error level -->
<filter type="log4net.Filter.LevelRangeFilter">
<levelMin value="ERROR" />
<levelMax value="ERROR" />
</filter>
</appender>
<!-- Set root logger level to ALL and its appenders to InfoAppender and ErrorAppender -->
<root>
<level value="ALL"/>
<!-- You can also use other levels such as DEBUG, WARN, FATAL etc. -->
<!-- See https://logging.apache.org/log4net/release/sdk/log4net.Core.Level.html for more details -->
<appender-ref ref ="InfoAppender"/>
<appender-ref ref ="ErrorAppender"/>
</root>
</log4net>
配置
在启动类中进行配置(Program.cs)
cs
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
#region 配置 log4Net 需要安装log4net、Microsoft.Extensions.Logging.Log4Net.AspNetCore
builder.Services.AddLogging(cfg =>
{
cfg.AddLog4Net();
//默认的配置文件路径是在根目录,且文件名为log4net.config
//如果文件路径或名称有变化,需要重新设置其路径或名称
//比如在项目根目录下创建一个名为cfg的文件夹,将log4net.config文件移入其中,并改名为log.config
//则需要使用下面的代码来进行配置
//cfg.AddLog4Net(new Log4NetProviderOptions()
//{
// Log4NetConfigFileName = "cfg/log.config",
// Watch = true
//});
});
#endregion
使用
cs
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private readonly ILogger<WeatherForecastController> _logger;
// 构造函数注入
public WeatherForecastController(ILogger<WeatherForecastController> logger, IUnitOfWork uow)
{
_logger = logger;
Uow = uow;
}
public IUnitOfWork Uow { get; }
[HttpGet("GetUsers")]
public async Task<ApiResponse> GetUsers()
{
IRepository<User> repository = Uow.GetRepository<User>();
IList<User> users = await repository.GetAllAsync(orderBy: f => f.OrderByDescending(x => x.UpdateDate));
_logger.LogInformation("查询所有用户");
return new ApiResponse(true, users);
}
}