1.安装NuGet包
2.准备Nlog的配置文件 nlog.config
<?xml version="1.0" encoding="utf-8" ?> <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"autoReload="true"throwExceptions="false"internalLogLevel="Info" internalLogFile="internal-nlog.txt"><!-- 定义日志输出目标 --><targets><target name="FileError" xsi:type="File" fileName="${basedir}/Logs/Error/${var:logfilename}_Error.txt"layout="${longdate} ${level:uppercase=true} ${message} ${exception}" archiveEvery="Day" archiveAboveSize="240" maxArchiveFiles="20" archiveFileName="${basedir}/Log/Error/${var:logfilename}_Error.{#}.txt" /><target name="FileWarn" xsi:type="File" fileName="${basedir}/Logs/Warn/${var:logfilename}_Warn.txt" layout="${longdate} ${message}"archiveEvery="Day" archiveAboveSize="240" maxArchiveFiles="20" archiveFileName="${basedir}/Log/Warn/${var:logfilename}_Warn.{#}.txt" /><target name="FileInfo" xsi:type="File" fileName="${basedir}/Logs/Info/${var:logfilename}_Info.txt" layout="${longdate} ${message}"archiveEvery="Day" archiveAboveSize="240" maxArchiveFiles="20" archiveFileName="${basedir}/Log/Info/${var:logfilename}_Info.{#}.txt" /><target name="FileDebug" xsi:type="File" fileName="${basedir}/Logs/Debug/${var:logfilename}_Debug.txt" layout="${longdate} ${message}"archiveEvery="Day" archiveAboveSize="240" maxArchiveFiles="20" archiveFileName="${basedir}/Log/Debug/${var:logfilename}_Debug.{#}.txt"/></targets><!-- 定义日志规则 --><rules><logger name="*" minlevel="Error" maxlevel="Fatal" writeTo="FileError" /><logger name="*" minlevel="Warn" maxlevel="Warn" writeTo="FileWarn" /><logger name="*" minlevel="Info" maxlevel="Info" writeTo="FileInfo" /><logger name="*" minlevel="Debug" maxlevel="Debug" writeTo="FileDebug" /></rules> </nlog>
3.添加注入NLog服务的扩展
private static string LogPath{get{return Path.Combine(AppContext.BaseDirectory, "nlog.config");}}public static ILoggingBuilder AddNLog(this ILoggingBuilder log,string? filename=null){//删除其他的日志记录提供程序 log.ClearProviders();LogManager.Configuration.LogFactory.Setup().LoadConfigurationFromFile(LogPath);LogManager.Configuration.Variables["logfilename"] = filename;//启用NLog作为日志记录的提供程序 log.AddNLogWeb(LogManager.Configuration);return log;}
4.Program.cs注入NLog服务
//日志 builder.Logging.AddNLog();
5.使用
[ApiController] [Route("[controller]")] public class UserController(ILogger<UserController> logger) : ControllerBase {[HttpGet("GetUserExit")]public void GetUserExit(string account){logger.LogInformation("调用方法->GetUserExit");} }
针对无法使用构造函数依赖注入使用日志的,建立如下Helper
public class LogHelper {private static string logPath{get { return Path.Combine(AppContext.BaseDirectory, "nlog.config"); }}private static ISetupBuilder _factory = LogManager.Configuration.LogFactory.Setup().LoadConfigurationFromFile(logPath);private static Logger _logger = null;/// <summary>/// 日志操作对象/// </summary>public static Logger Log{get{if (_logger == null) _logger = _factory.LogFactory.GetCurrentClassLogger();return _logger;}}}
如在Program中调用