1.首先下载log4ne的包:
2.添加配置文件log4net.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<!-- This section contains the log4net configuration settings -->
<log4net>
<appender name="ErrorLogFileAppender" type="log4net.Appender.RollingFileAppender">
<!--日志输入路径-->
<file value="ErrorLog/" />
<!--日志是否追加到文件-->
<appendToFile value="true" />
<!--按照何种方式产生多个日志文件(日期[Date],文件大小[Size],混合[Composite])-->
<rollingStyle value="Composite" />
<!--是否只写到一个文件中-->
<staticLogFileName value="false" />
<!--防止多线程时不能写Log,官方说线程非安全-->
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<!--按日期命名文件-->
<datePattern value="yyyyMMdd'.log'" />
<!--最多产生文件数超过的话保留最新-->
<maxSizeRollBackups value="100" />
<!--每个文件的大小。只在混合方式与文件大小方式下使用。超出大小后在所有文件名后自动增加正整数重新命名,数字最大的最早写入。可用的单位:KB|MB|GB。不要使用小数,否则会一直写入当前日志-->
<maximumFileSize value="50MB" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %message%newline" />
<header value="
----------------------header--------------------------
" />
<footer value="
----------------------footer--------------------------
"/>
</layout>
<!--定义日志级别根据不同的级别调用不同的配置写入-->
<filter type="log4net.Filter.LevelRangeFilter">
<param name="LevelMin" value="Error" />
<param name="LevelMax" value="Error" />
</filter>
</appender>
<appender name="DeBugLogFileAppender" type="log4net.Appender.RollingFileAppender">
<!--日志输入路径-->
<file value="DeBugLog/" />
<!--日志是否追加到文件-->
<appendToFile value="true" />
<!--按照何种方式产生多个日志文件(日期[Date],文件大小[Size],混合[Composite])-->
<rollingStyle value="Composite" />
<!--是否只写到一个文件中-->
<staticLogFileName value="false" />
<!--防止多线程时不能写Log,官方说线程非安全-->
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<!--按日期命名文件-->
<datePattern value="yyyyMMdd'.log'" />
<!--最多产生文件数超过的话保留最新-->
<maxSizeRollBackups value="100" />
<!--每个文件的大小。只在混合方式与文件大小方式下使用。超出大小后在所有文件名后自动增加正整数重新命名,数字最大的最早写入。可用的单位:KB|MB|GB。不要使用小数,否则会一直写入当前日志-->
<maximumFileSize value="50MB" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %message%newline" />
<header value="
----------------------header--------------------------
" />
<footer value="
----------------------footer--------------------------
"/>
</layout>
<!--定义日志级别根据不同的级别调用不同的配置写入-->
<filter type="log4net.Filter.LevelRangeFilter">
<param name="LevelMin" value="DeBug" />
<param name="LevelMax" value="DeBug" />
</filter>
</appender>
<!-- Setup the root category, add the appenders and set the default level -->
<root>
<level value="All" />
<appender-ref ref="ErrorLogFileAppender" />
<appender-ref ref="DeBugLogFileAppender" />
</root>
</log4net>
</configuration>
3.添加日志帮助类
using log4net.Config;
using log4net;
namespace CodeIdentify
{
public class LoggerHelper
{
private ILog logger;
public LoggerHelper()
{
if (logger == null)
{
var repository = LogManager.CreateRepository("NETCoreRepository");
//log4net从log4net.config文件中读取配置信息
XmlConfigurator.Configure(repository, new FileInfo("log4net.config"));
logger = LogManager.GetLogger(repository.Name, "Logger");
}
}
/// <summary>
/// Debug日志
/// </summary>
/// <param name="data">调试数据</param>
public void Debug(object data)
{
logger.Debug(data);
}
/// <summary>
/// 普通日志
/// </summary>
/// <param name="controller">控制器</param>
/// <param name="exception">catch异常信息</param>
public void Info(string controller, Exception exception = null)
{
if (exception == null)
logger.Info(controller);
else
logger.Info(controller, exception);
}
/// <summary>
/// 告警日志
/// </summary>
/// <param name="controller"></param>
/// <param name="exception"></param>
public void Warn(string controller, Exception exception = null)
{
if (exception == null)
logger.Warn(controller);
else
logger.Warn(controller, exception);
}
/// <summary>
/// 错误日志
/// </summary>
/// <param name="controller"></param>
/// <param name="exception"></param>
public void Error(string controller, Exception exception = null)
{
if (exception == null)
logger.Error(controller);
else
logger.Error(controller, exception);
}
}
}
4.在服务中采用单例生命周期注入
builder.Services.AddSingleton(typeof(LoggerHelper));
5.添加全局异常过滤器
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System.Net;
namespace CodeIdentify
{
public class GlobalExceptionFilter : IExceptionFilter
{
private readonly LoggerHelper _loggerHelper;
public GlobalExceptionFilter(LoggerHelper loggerHelper)
{
_loggerHelper= loggerHelper;
}
public void OnException(ExceptionContext context)
{
var exception = context.Exception;
_loggerHelper.Error(context.HttpContext.Request.Method, exception);
context.ExceptionHandled = true; // 标记已处理异常
}
}
}
6.注入过滤器服务
builder.Services.AddControllers(options =>
{
options.Filters.Add<GlobalExceptionFilter>();
});
7.使用
using CodeIdentify.Servers;
using Microsoft.AspNetCore.Mvc;
namespace CodeIdentify.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class CodeIdentityController : ControllerBase
{
private readonly IBaiDuCodeIdentity _baiDuCodeIdentity;
public CodeIdentityController(IBaiDuCodeIdentity baiDuCodeIdentity)
{
_baiDuCodeIdentity = baiDuCodeIdentity;
}
[HttpPost]
public async Task<IActionResult> GetCode([FromBody] string url)
{
if(string.IsNullOrWhiteSpace(url)) throw new ArgumentNullException(nameof(url));
return Ok();
}
}
}
日志截图: