ASP.NET Core 有內置的log組件,遺憾的是看了微軟官方文檔,貌似無法直接將日誌存於文件或資料庫,只能由自己實現或引用第三方日誌組件。 以下為Nlog和log4net的使用記錄 Nlog使用 搜索添加Nuget包 搜索添加Nuget包 新建一個xml文件,並改名為nlog.config 新 ...
ASP.NET Core 有內置的log組件,遺憾的是看了微軟官方文檔,貌似無法直接將日誌存於文件或資料庫,只能由自己實現或引用第三方日誌組件。
以下為Nlog和log4net的使用記錄
Nlog使用
-
搜索添加Nuget包
Nlog
Nlog.Web.AspNetCore
-
新建一個xml文件,並改名為nlog.config
XML內容如下(可配置日誌目錄名稱、輸出格式):
<?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" internalLogLevel="Warn" internalLogFile="internal-nlog.txt"> <!--define various log targets--> <targets>
<!--write logs to file--> <target xsi:type="File" name="allfile" fileName="Logs/service-${shortdate}.log" layout="${longdate}|${logger}|${uppercase:${level}}|${message} ${exception}" />
</targets>
<rules> <!--All logs, including from Microsoft--> <logger name="*" minlevel="Trace" writeTo="allfile" /> </rules> </nlog>
-
將nlog.config設置輸出到目錄
-
在Startup類中配置
需要引入命名空間:
using NLog.Extensions.Logging;
using NLog.Web;
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactor) { //使用Nlog loggerFactor.AddNLog(); //引入配置文件 env.ConfigureNLog("nlog.config"); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); } app.UseStaticFiles(); app.UseCookiePolicy(); app.UseMvc(); }
-
代碼中的使用
有兩中方式如下:
1、註入形式
public class IndexModel : PageModel { private ILogger<IndexModel> _logger; public IndexModel(ILogger<IndexModel> logger) { _logger = logger; } public string Customer { get; set; } public void OnGet() { _logger.LogWarning("111111111111111111111"); Customer = "123456"; } }
2、獲取實例形式
private static Logger Logger = LogManager.GetCurrentClassLogger(); public static void Main(string[] args) { Logger.Error("22222222222222222222222222222"); Logger.Info("333333333333333333333333333333"); }
log4net
log4net已支持net core,來看下在net core下是如何配置的,與之前的版本還是有一點的區別
-
使用慣例,引用Nuget
log4net
-
新建配置文件
<?xml version="1.0" encoding="utf-8" ?> <configuration> <!-- This section contains the log4net configuration settings --> <log4net> <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender"> <layout type="log4net.Layout.PatternLayout" value="%date [%thread] %-5level %logger - %message%newline" /> </appender> <appender name="FileAppender" type="log4net.Appender.FileAppender"> <file value="log-file.log" /> <appendToFile value="true" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" /> </layout> </appender> <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender"> <file value="logs/" /> <appendToFile value="true" /> <rollingStyle value="Date" /> <staticLogFileName value="false" /> <datePattern value="yyyy-MM-dd'.log'" /> <maxSizeRollBackups value="7" /> <maximumFileSize value="1MB" /> <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="ConsoleAppender" /> <appender-ref ref="FileAppender" /> <appender-ref ref="RollingLogFileAppender" /> </root> </log4net> </configuration>
配置文件的相關說明,可以查看另一篇文章 點我跳轉
-
在StartUp.cs中配置log4Net
public static ILoggerRepository repository { get; set; }
public Startup(IConfiguration configuration) { Configuration = configuration; //log4net repository = LogManager.CreateRepository("NETCoreRepository"); //指定配置文件 XmlConfigurator.Configure(repository, new FileInfo("log4net.config")); }
-
Controller中的使用
private ILog log = LogManager.GetLogger(Startup.repository.Name, typeof(ValuesController)); [HttpGet] public ActionResult<IEnumerable<string>> Get() { log.Info(1111111111111111111); return new string[] { "value1", "value2" }; }
-
控制臺中的使用
ILoggerRepository repository = LogManager.CreateRepository("NETCoreRepository");
XmlConfigurator.Configure(repository, new FileInfo("log4net.config"));
ILog log = LogManager.GetLogger(repository.Name,"NETCorelog4net"); log.Info("test log");