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");

最新文章

  1. shell 简单计算脚本
  2. 查看centos系统版本
  3. APIO2015 酱油记
  4. 最短JS判断是否为IE6(IE的写法)
  5. CS小分队第一阶段冲刺站立会议(5月8日)
  6. 拥抱ARM妹纸第二季 之 第二次 约会需要浪漫,这么大灯泡怎么弄?
  7. unity 退到桌面的 OnApplicationPause
  8. PHP文件操作,多行句子的读取,file()函数,file_get_contents()函数,file_put_contents()函数,is_file,统计网站pv (访问量),文件的复制 copy,文件重命名 rename,删除文件 unlink
  9. 【转载】什么是Windows USB设备路径,它是如何格式化的?
  10. HDU 6437 Problem L.Videos (最大费用)【费用流】
  11. ubuntu所有php扩展php-7.0扩展列表
  12. 多线程Thread类的方法
  13. SQL 必知必会&#183;笔记&lt;11&gt;创建高级联结
  14. 预期结果 参数化parametrize
  15. 搭建ReactNative时的最普遍的错误—— &quot;:CFBundleIdentifier&quot;, Does Not Exist
  16. JavaScript实现链式调用
  17. 使用云负载时将http的请求转发至https时报错:“ERR_TOO_MANY_REDIRECTS”!
  18. 全局结果集,带参数的结果集和动态结果集(struts2)
  19. Romantic---hdu2669(扩展欧几里德模板)
  20. spring boot配置springMVC拦截器

热门文章

  1. 物流的纯css实现方法
  2. 15.linux基础
  3. Java (三、数组)
  4. 关于html以及js相关格式验证的记录
  5. crontab定时任务, 定时到秒
  6. 第二章:第一个Netty程序
  7. 第八章——降维(Dimensionality Reduction)
  8. Autopep8的使用
  9. LeetCode Javascript实现 258. Add Digits 104. Maximum Depth of Binary Tree 226. Invert Binary Tree
  10. anguments