需要安装NuGet包,明细如下:
文件名称 log4net.config
,默认可以放在与启动类Program.cs
同级目录下
<log4net>
<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>
<filter type="log4net.Filter.LevelRangeFilter">
<levelMin value="INFO" />
<levelMax value="INFO" />
filter>
appender>
<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>
<filter type="log4net.Filter.LevelRangeFilter">
<levelMin value="ERROR" />
<levelMax value="ERROR" />
filter>
appender>
<root>
<level value="ALL"/>
<appender-ref ref ="InfoAppender"/>
<appender-ref ref ="ErrorAppender"/>
root>
log4net>
在启动类中进行配置(Program.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
[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);
}
}