asp.net core 集成 log4net 日志框架

Intro

在 asp.net core 中有些日志我们可能想输出到数据库或文件或elasticsearch等,如果不自己去实现一个 LoggerProvider 的话就需要借助第三方日志框架实现了,而一些第三方框架的实现大多比较完善和成熟,不失为一个好办法。

自己写了一个 log4net 的扩展 WeihanLi.Common.Logging.Log4Net,提供了在 .net core 中使用 log4net 的扩展

安装 nuget 包

通过 nuget 安装 WeihanLi.Common.Logging.Log4Net

使用

基本使用

ILoggerFactory loggerFactory = new LoggerFactory();
loggerFactory.AddLog4Net(); // loggerFactory.AddLog4Net(log4netConfigFilePath);

你可以在 asp.net core 应用里你的 Startup 文件中使用下面代码进行配置

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddLog4Net(); // loggerFactory.AddLog4Net(log4netConfigFilePath); // ...
}

默认使用当前目录下的 log4net.config 文件作为 log4net 的配置文件,如果不是需要自己设置 log4net 配置文件的路径。

log4net 配置参考 示例配置

源码解析

项目源码

Log4NetLoggerProvider

  • 实现记录日志的 ILogger
    internal class Log4NetLogger : ILogger
{
private readonly ILog _logger; public Log4NetLogger(string name) => _logger = LogManager.GetLogger(ApplicationHelper.ApplicationName, name); public IDisposable BeginScope<TState>(TState state) => NullScope.Instance; public bool IsEnabled(LogLevel logLevel)
{
switch (logLevel)
{
case LogLevel.Critical:
return _logger.IsFatalEnabled; case LogLevel.Debug:
case LogLevel.Trace:
return _logger.IsDebugEnabled; case LogLevel.Error:
return _logger.IsErrorEnabled; case LogLevel.Information:
return _logger.IsInfoEnabled; case LogLevel.Warning:
return _logger.IsWarnEnabled; case LogLevel.None:
return false; default:
throw new ArgumentOutOfRangeException(nameof(logLevel));
}
} public void Log<TState>(LogLevel logLevel, EventId eventId, TState state,
Exception exception, Func<TState, Exception, string> formatter)
{
if (!IsEnabled(logLevel))
{
return;
} if (formatter == null)
{
throw new ArgumentNullException(nameof(formatter));
} var message = formatter(state, exception); if (!(string.IsNullOrEmpty(message) && exception == null))
{
switch (logLevel)
{
case LogLevel.Critical:
_logger.Fatal(message, exception);
break; case LogLevel.Debug:
case LogLevel.Trace:
_logger.Debug(message, exception);
break; case LogLevel.Error:
_logger.Error(message, exception);
break; case LogLevel.Information:
_logger.Info(message, exception);
break; case LogLevel.Warning:
_logger.Warn(message, exception);
break; default:
_logger.Warn($"Encountered unknown log level {logLevel}, writing out as Info.");
_logger.Info(message, exception);
break;
}
}
}
}
  • 实现提供 logger 的 ILoggerProvider
    [ProviderAlias("log4net")]
internal class Log4NetLoggerProvider : ILoggerProvider
{
private readonly ConcurrentDictionary<string, Log4NetLogger> _loggers =
new ConcurrentDictionary<string, Log4NetLogger>(StringComparer.Ordinal); public Log4NetLoggerProvider(string confFilePath)
{
if (null == LogManager.GetAllRepositories()?.FirstOrDefault(_ => _.Name == ApplicationHelper.ApplicationName))
{
XmlConfigurator.ConfigureAndWatch(LogManager.CreateRepository(ApplicationHelper.ApplicationName), new FileInfo(confFilePath));
}
} public void Dispose() => _loggers.Clear(); public ILogger CreateLogger(string categoryName) => _loggers.GetOrAdd(categoryName, loggerName => new Log4NetLogger(loggerName));
}
  • 添加 ILoggerFactory 扩展
    public static class Log4NetLoggerFactoryExtensions
{
public static ILoggerFactory AddLog4Net(this ILoggerFactory factory)
{
factory.AddProvider(new Log4NetLoggerProvider(ApplicationHelper.MapPath("log4net.config"))); return factory;
} public static ILoggerFactory AddLog4Net(this ILoggerFactory factory, string configFile)
{
factory.AddProvider(new Log4NetLoggerProvider(configFile)); return factory;
}
}

Memo

如果有什么问题或建议,欢迎指出

asp.net core 集成 log4net 日志框架的更多相关文章

  1. Asp.net core 使用log4net作为日志组件,记录日志到本地。

    原文:Asp.net core 使用log4net作为日志组件,记录日志到本地. GitHub demo :https://github.com/zhanglilong23/Asp.NetCore.D ...

  2. ABP官方文档翻译 6.2.1 ASP.NET Core集成

    ASP.NET Core 介绍 迁移到ASP.NET Core? 启动模板 配置 启动类 模块配置 控制器 应用服务作为控制器 过滤器 授权过滤器 审计Action过滤器 校验过滤器 工作单元Acti ...

  3. ASP.NET Core 异常处理与日志记录

    1. ASP.NET Core 异常处理与日志记录 1.1. 异常处理 1.1.1. 异常产生的原因及处理 1.1.2. ASP.NET Core中启动开发人员异常页面 1.2. 日志记录 1.2.1 ...

  4. [Abp 源码分析]十七、ASP.NET Core 集成

    0. 简介 整个 Abp 框架最为核心的除了 Abp 库之外,其次就是 Abp.AspNetCore 库了.虽然 Abp 本身是可以用于控制台程序的,不过那样的话 Abp 就基本没什么用,还是需要集合 ...

  5. asp.net core集成CAP(分布式事务总线)

    一.前言 感谢杨晓东大佬为社区贡献的CAP开源项目,传送门在此:.NET Core 事件总线,分布式事务解决方案:CAP 以及 如何在你的项目中集成 CAP[手把手视频教程],之前也在工作中遇到分布式 ...

  6. 玩转ASP.NET Core中的日志组件

    简介 日志组件,作为程序员使用频率最高的组件,给程序员开发调试程序提供了必要的信息.ASP.NET Core中内置了一个通用日志接口ILogger,并实现了多种内置的日志提供器,例如 Console ...

  7. asp.net core 系列 13 日志

    一.概述 ASP.NET Core 支持适用于各种内置和第三方日志记录, 供程序的日志记录 API,本文介绍了如何将日志记录 API 与内置提供程序一起使用.对于第三方日志记录提供程序使用,文章最后有 ...

  8. asp.net core集成MongoDB

    0.目录 整体架构目录:ASP.NET Core分布式项目实战-目录 一.前言及MongoDB的介绍 最近在整合自己的框架,顺便把MongoDBD的最简单CRUD重构一下作为组件化集成到asp.net ...

  9. (14)ASP.NET Core 中的日志记录

    1.前言 ASP.NET Core支持适用于各种内置和第三方日志记录提供应用程序的日志记录API.本文介绍了如何将日志记录API与内置提供应用程序一起使用. 2.添加日志提供程序 日志记录提供应用程序 ...

随机推荐

  1. clang如何获得程序控制流图

    在低版本的clag中,可以直接clang -cc1 -analyze -cfg-dump 1.c来获得程序控制流图,但较高版本后就不行了 另外clang -cc1默认仅限当前目录,所以会出现fata ...

  2. 企业移动应用和Smobiler

    www.smobiler.com     什么是企业移动应用?     能够通过一种方式来为客户.合作伙伴和员工交付信息和服务,从而帮助其增加收入,提高业务敏捷性和生产力的移动端产品,我们称之为企业移 ...

  3. Java之mybatis详解

    文章大纲 一.mybatis介绍二.mybatis代码实战三.项目源码下载四.参考文章   一.mybatis介绍 1. mybatis是什么?   mybatis是一个持久层的框架,是apache下 ...

  4. Android 项目中用得最多最火的第三方框架可能都在这里了

    分类 二级分类 框架名称 简介 Star 数 最近更新 UI 刷新 SmartRefreshLayout 智能下拉刷新框架 14k 18天 UI 刷新 Android-PullToRefresh 比较 ...

  5. iOS屏幕适配 支持新手机 iPhone XR iPhone XS 超简单

    随着苹果爸爸发布了 超牛叉的iPhone iPhone X .iPhone XR.iPhone XS .iPhone XS Max.开发者的适配工作要开始了. 停,

  6. VIVADO时序约束及STA基础

    一.前言 无论是FPGA应用开发还是数字IC设计,时序约束和静态时序分析(STA)都是十分重要的设计环节.在FPGA设计中,可以在综合后和实现后进行STA来查看设计是否能满足时序上的要求.本文阐述基本 ...

  7. Oracle设置主键自增

    oracle没有mysql那样可以有自增主键,需要自己通过创建序列才能实现自增 /*创建自增序列*/ CREATE SEQUENCE CMB_CHINA_CITYS_ID MINVALUE --最小值 ...

  8. 使用whistle模拟cgi接口异常:错误码、502、慢网速、超时

    绝大多数程序只考虑了接口正常工作的场景,而用户在使用我们的产品时遇到的各类异常,全都丢在看似 ok 的 try catch 中.如果没有做好异常的兼容和兜底处理,会极大的影响用户体验,严重的还会带来安 ...

  9. 阿里巴巴excel工具easyexcel 助你快速简单避免OOM

    Java解析.生成Excel比较有名的框架有Apache poi.jxl.但他们都存在一个严重的问题就是非常的耗内存,poi有一套SAX模式的API可以一定程度的解决一些内存溢出的问题,但POI还是有 ...

  10. IDLE打开Python报错 api-ms-win-crt-runtimel1-1-0.dll缺失的解决方案

    1.此方法转载至 http://blog.csdn.net/lt_java13/article/details/78814676 2.把C:\Windows\SysWOW64的api-ms-win-c ...