码迷,mamicode.com
首页 > Web开发 > 详细

.NET CORE搭建Log日志

时间:2020-01-07 17:48:08      阅读:349      评论:0      收藏:0      [点我收藏+]

标签:out   remove   filename   spl   html   private   close   nuget   source   

原文出自https://www.cnblogs.com/AprilBlank/p/11282345.html 非常感谢。

1.工具->NuGet包管理器->管理解决方案的NuGet程序包 找到log4net下载

2.在Startup.cs中配置注入

技术图片
 public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
            repository = LogManager.CreateRepository("AprilLog");

            XmlConfigurator.Configure(repository, new FileInfo("Config/log4net.config"));//配置文件路径可以自定义
            BasicConfigurator.Configure(repository);
        }
        //log4net日志
        public static ILoggerRepository repository { get; set; }
        public IConfiguration Configuration { get; }
Startup

3.在工程目录下新建一个config文件

技术图片

 

 代码如下

技术图片
<?xml version="1.0" encoding="utf-8"?>
<configuration>

  <!-- To customize the asp.net core module uncomment and edit the following section. 
  For more info see https://go.microsoft.com/fwlink/?linkid=838655 -->
  <!--
  <system.webServer>
    <handlers>
      <remove name="aspNetCore"/>
      <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified"/>
    </handlers>
    <aspNetCore processPath="%LAUNCHER_PATH%" arguments="%LAUNCHER_ARGS%" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" />
  </system.webServer>
  -->
<!-- This section contains the log4net configuration settings -->
  <log4net debug="false">
    <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
      <lockingModel type="log4net.Appender.FileAppender+MinimalLock" /><!--很关键的一句,让日志文件不被占用-->
      <file value="logs/" /> <!-- 日志生成文件路径 -->
      <appendToFile value="true" /> 
      <rollingStyle value="Composite" />
      <staticLogFileName value="false" />
      <datePattern value="yyyyMMdd‘.log‘" /> <!-- 日志文件名称格式 -->
      <maxSizeRollBackups value="10" />
      <maximumFileSize value="10MB" /> <!-- 最大文件大小,达到后生成新文件 -->
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger - %message%newline" /> <!-- 生成日志格式 -->
      </layout>
    </appender>

    <!-- Setup the root category, add the appenders and set the default level -->
    <root>
      <level value="ALL" />  <!-- 日志等级 -->
      <appender-ref ref="RollingLogFileAppender" /> 
    </root>

  </log4net>
</configuration>
log4net.config

4.在需要使用的地方创建Log对象 从而使用Info方法记录。

技术图片
private ILog log = LogManager.GetLogger(Startup.repository.Name, "标题");
log.Info(ex.Message, ex);
使用Log

5.会在工程项目中出现Log文件

技术图片

亲测可用。

.NET CORE搭建Log日志

标签:out   remove   filename   spl   html   private   close   nuget   source   

原文地址:https://www.cnblogs.com/cdjbolg/p/12162806.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!