.net core 杂记:日记记录

时间:2024-04-08 11:05:31

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("");
Customer = "";
}
}

2、获取实例形式

private static Logger Logger = LogManager.GetCurrentClassLogger();
public static void Main(string[] args)
{
Logger.Error("");
Logger.Info("");
}

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="" />
<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();
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");