.NET CORE 使用log4net 教程

笑着哭i 提交于 2020-01-27 08:42:44

第一步NuGet,在公共类库引用log4net的文件,当然你想在其它类库也可以引用,但建议是在公共类库引用。

第二步在WebApi项目下建立log4net.config 文件,复制以下内容到这个文件

<?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="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">

      <file value="logfile/" />
      <appendToFile value="true" />
      <rollingStyle value="Composite" />
      <staticLogFileName value="false" />
      <datePattern value="yyyyMMdd'.log'" />
      <maxSizeRollBackups value="10" />
      <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 文件下添加如下代码,标红是我添加的

  public class Startup
    {
        public static ILoggerRepository repository { get; set; }
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
            repository = LogManager.CreateRepository("GD.Core");
            //指定配置文件
            XmlConfigurator.Configure(repository, new FileInfo("log4net.config"));

        }

  public IServiceProvider ConfigureServices(IServiceCollection services)
        {

          //log日志注入
            services.AddSingleton<ILogger, LogHelper>();

第四步在Services层 添加如下代码

namespace Guet.Services
{
    /// <summary>
    /// 公告表
    /// </summary>    
    public class SysNoticeServices : BaseServices<SysNotice>, ISysNoticeServices
    {

        private ISysNoticeRepository dal;
        private ISysUserRepository SysUserRepository;
        private IMapper Mapper;
        private readonly IUnitOfWork UnitOfWork;
        private ILogger Logger;
        public SysNoticeServices(IUnitOfWork UnitOfWork, ISysNoticeRepository dal, IMapper Mapper, ISysUserRepository SysUserRepository, ILogger Logger)
        {
            this.dal = dal;
            base.baseDal = dal;
            this.Mapper = Mapper;
            this.UnitOfWork = UnitOfWork;
            this.SysUserRepository = SysUserRepository;
            this.Logger = Logger;
        }

第五步,就可以直接通过Logger.Debug();

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!