.Net5 WebApi中使用log4net记录日志(已在生产环境中使用)

本文讲解在.Net5 WebApi中使用log4net记录日志(已在生产环境中使用)

  • 安装Log4Net
  • 编写Log4Net配置文件(注意:要修改配置文件属性为始终复制)
  • 编写Log4Net初始化类LoggerInit(用来初始化Log4Net加载配置文件)
  • 在Startup构造函数中初始化/启动日志
  • 开发记录日志工具类供业务端调用
    • 定义记录日志接口ILoggerUtil
    • 定义记录日志接口实现类LoggerUtil
  • 如何使用工具类记录日志?
    • 在要使用的地方注入工具类
    • 使用工具类记录日志

安装Log4Net

使用Nuget安装Log4Net:

install-package Microsoft.Extensions.Logging.Log4Net.AspNetCore
只安装这一个即可,其他的相关log4net依赖都会被自动安装进来

编写Log4Net配置文件(注意:要修改配置文件属性为始终复制)


<log4net>
	<appender name="rollingAppender" type="log4net.Appender.RollingFileAppender">

		<file value="Log//log.txt" />
		<appendToFile value="true" />
		<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
		<rollingStyle value="Date" />
		<datePattern value="yyyy-MM-dd".txt"" />
		<StaticLogFileName value="false"/>
		<maxSizeRollBackups value="500" />
		<maximumFileSize value="10MB" />
		<staticLogFileName value="true" />

		<filter type="log4net.Filter.LevelRangeFilter">
			<param name="LevelMin" value="DEBUG" />
			<param name="LevelMax" value="FATAL" />
		filter>
		<layout type="log4net.Layout.PatternLayout">
			<conversionPattern value="%date [%thread] %-5level %logger - %message%newline"/>
		layout>
	appender>
	<root>
		<priority value="ALL"/>
		<level value="ALL"/>
		<appender-ref ref="rollingAppender" />
	root>
log4net>

编写Log4Net初始化类LoggerInit(用来初始化Log4Net加载配置文件)

using log4net;
using log4net.Config;
using log4net.Repository;
using System.IO;
using Levox.Framework.Core.Models.App;
using Levox.Framework.Core.CommonUtils;

namespace Levox.Framework.Core.Logger
{
    /// 
    /// 日志初始化   LastUpdateDate:2021-03-30 16:57:39.074  Author:Lingbug
    /// 
    public static class LoggerInit
    {
        /// 
        /// 日志仓储
        /// 
        public static ILoggerRepository LoggerRepository { get; set; }

        /// 
        /// 初始化日志   LastUpdateDate:2021-03-30 16:59:46.785  Author:Lingbug
        /// 
        public static void Init()
        {
            //创建仓储
            LoggerRepository = LogManager.CreateRepository(nameof(LoggerRepository));
            //配置文件路径
            string logConfigPath = FileUtil.ComboPath(ApplicationData.RootPath, "Config", "log.config");
            //配置文件
            var logConfigFile = new FileInfo(logConfigPath);
            //加载日志配置
            XmlConfigurator.Configure(LoggerRepository, logConfigFile);
        }
    }
}

在Startup构造函数中初始化/启动日志

LoggerInit.Init();

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Levox.Framework.Model.Input;
using Levox.Framework.WebApi.Extensions;
using Autofac;
using Levox.Framework.Core.Logger;
using Levox.Framework.Core.ServiceInject;

namespace Levox.NewERP.WebApi
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
            //一行代码启动日志(注意配置文件路径必须为Config/log.config,且属性改为始终复制)
            LoggerInit.Init();
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {

        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            //一行代码启动框架
            app.UseErpConfiguration(env, new UseErpConfigurationOption());
        }

        /// 
        /// 定义此方法,框架自动调用注入所有系统服务   LastUpdateDate:2021-04-01 18:30:41.633  Author:Lingbug
        /// 
        /// 
        public void ConfigureContainer(ContainerBuilder builder) => builder.RegisterModule<ErpServiceInjectModule>();
    }
}

开发记录日志工具类供业务端调用

定义记录日志接口ILoggerUtil

using System;
using Levox.Framework.Core.Models.Inject;

namespace Levox.Framework.Core.Logger
{
    /// 
    /// 日志工具类   LastUpdateDate:2021-03-30 17:02:39.554  Author:Lingbug
    /// 
    public interface ILoggerUtil : IErpSingletonApplicationService
    {
        /// 
        /// 记录调试日志   LastUpdateDate:2021-03-30 17:21:52.400  Author:Lingbug
        /// 
        /// 
        /// 
        void Debug(object message, Exception exception = null);

        /// 
        /// 记录信息日志   LastUpdateDate:2021-03-30 17:22:16.816  Author:Lingbug
        /// 
        /// 
        /// 
        void Info(object message, Exception exception = null);

        /// 
        /// 记录警告日志   LastUpdateDate:2021-03-30 17:22:31.272  Author:Lingbug
        /// 
        /// 
        /// 
        void Warn(object message, Exception exception = null);

        /// 
        /// 记录错误日志   LastUpdateDate:2021-03-30 17:22:43.240  Author:Lingbug
        /// 
        /// 
        /// 
        void Error(object message, Exception exception = null);

        /// 
        /// 记录致命异常日志   LastUpdateDate:2021-03-30 17:23:05.379  Author:Lingbug
        /// 
        /// 
        /// 
        void Fatal(object message, Exception exception = null);
    }
}

定义记录日志接口实现类LoggerUtil

using log4net;
using System;
using System.Diagnostics;

namespace Levox.Framework.Core.Logger
{
    /// 
    /// 日志工具类   LastUpdateDate:2021-03-30 16:55:48.940  Author:Lingbug
    /// 
    public class LoggerUtil : ILoggerUtil
    {
        /// 
        /// 记录调试日志   LastUpdateDate:2021-03-30 17:21:52.400  Author:Lingbug
        /// 
        /// 
        /// 
        public void Debug(object message, Exception exception = null)
        {
            var logger = GetLogger();
            if (exception == null)
                logger.Debug(message);
            else
                logger.Debug(message, exception);
        }

        /// 
        /// 记录信息日志   LastUpdateDate:2021-03-30 17:22:16.816  Author:Lingbug
        /// 
        /// 
        /// 
        public void Info(object message, Exception exception = null)
        {
            var logger = GetLogger();
            if (exception == null)
                logger.Info(message);
            else
                logger.Info(message, exception);
        }

        /// 
        /// 记录警告日志   LastUpdateDate:2021-03-30 17:22:31.272  Author:Lingbug
        /// 
        /// 
        /// 
        public void Warn(object message, Exception exception = null)
        {
            var logger = GetLogger();
            if (exception == null)
                logger.Warn(message);
            else
                logger.Warn(message, exception);
        }

        /// 
        /// 记录错误日志   LastUpdateDate:2021-03-30 17:22:43.240  Author:Lingbug
        /// 
        /// 
        /// 
        public void Error(object message, Exception exception = null)
        {
            var logger = GetLogger();
            if (exception == null)
                logger.Error(message);
            else
                logger.Error(message, exception);
        }

        /// 
        /// 记录致命异常日志   LastUpdateDate:2021-03-30 17:23:05.379  Author:Lingbug
        /// 
        /// 
        /// 
        public void Fatal(object message, Exception exception = null)
        {
            var logger = GetLogger();
            if (exception == null)
                logger.Fatal(message);
            else
                logger.Fatal(message, exception);
        }

        /// 
        /// 获取logger   LastUpdateDate:2021-03-30 17:20:43.161  Author:Lingbug
        /// 
        /// 
        private ILog GetLogger()
        {
            //读取调用日志的方法
            var callMethod = new StackTrace().GetFrame(2).GetMethod();
            //获取日志编写器
            return LogManager.GetLogger(LoggerInit.LoggerRepository.Name, callMethod.DeclaringType);
        }
    }
}

如何使用工具类记录日志?

在要使用的地方注入工具类

        /// 
        /// 日志服务   LastUpdateDate:2021-04-09 11:48:04.431  Author:Lingbug
        /// 
        public ILoggerUtil LoggerUtil { get; set; }

使用工具类记录日志

LoggerUtil.Debug("使用工具类记录日志");

你可能感兴趣的:(.Net3.1/.Net5,c#)