asp.net core 集成 log4net 日志框架
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 配置参考 示例配置
源码解析
- 实现记录日志的 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 日志框架的更多相关文章
- Asp.net core 使用log4net作为日志组件,记录日志到本地。
原文:Asp.net core 使用log4net作为日志组件,记录日志到本地. GitHub demo :https://github.com/zhanglilong23/Asp.NetCore.D ...
- ABP官方文档翻译 6.2.1 ASP.NET Core集成
ASP.NET Core 介绍 迁移到ASP.NET Core? 启动模板 配置 启动类 模块配置 控制器 应用服务作为控制器 过滤器 授权过滤器 审计Action过滤器 校验过滤器 工作单元Acti ...
- ASP.NET Core 异常处理与日志记录
1. ASP.NET Core 异常处理与日志记录 1.1. 异常处理 1.1.1. 异常产生的原因及处理 1.1.2. ASP.NET Core中启动开发人员异常页面 1.2. 日志记录 1.2.1 ...
- [Abp 源码分析]十七、ASP.NET Core 集成
0. 简介 整个 Abp 框架最为核心的除了 Abp 库之外,其次就是 Abp.AspNetCore 库了.虽然 Abp 本身是可以用于控制台程序的,不过那样的话 Abp 就基本没什么用,还是需要集合 ...
- asp.net core集成CAP(分布式事务总线)
一.前言 感谢杨晓东大佬为社区贡献的CAP开源项目,传送门在此:.NET Core 事件总线,分布式事务解决方案:CAP 以及 如何在你的项目中集成 CAP[手把手视频教程],之前也在工作中遇到分布式 ...
- 玩转ASP.NET Core中的日志组件
简介 日志组件,作为程序员使用频率最高的组件,给程序员开发调试程序提供了必要的信息.ASP.NET Core中内置了一个通用日志接口ILogger,并实现了多种内置的日志提供器,例如 Console ...
- asp.net core 系列 13 日志
一.概述 ASP.NET Core 支持适用于各种内置和第三方日志记录, 供程序的日志记录 API,本文介绍了如何将日志记录 API 与内置提供程序一起使用.对于第三方日志记录提供程序使用,文章最后有 ...
- asp.net core集成MongoDB
0.目录 整体架构目录:ASP.NET Core分布式项目实战-目录 一.前言及MongoDB的介绍 最近在整合自己的框架,顺便把MongoDBD的最简单CRUD重构一下作为组件化集成到asp.net ...
- (14)ASP.NET Core 中的日志记录
1.前言 ASP.NET Core支持适用于各种内置和第三方日志记录提供应用程序的日志记录API.本文介绍了如何将日志记录API与内置提供应用程序一起使用. 2.添加日志提供程序 日志记录提供应用程序 ...
随机推荐
- Redis的正确使用姿势
前言 说到分布式缓存,可能大多数人脑海浮现的就是redis了,为什么redis能够在竞争激烈的缓存大战中脱颖而出呢?原因无非有一下几点:性能好,丰富的特性跟数据结构,api操作简单.但是用的人多了,就 ...
- FontAwesome 图标字体库的使用
在前端开发中,许多新手常会遇见一个问题,参考的网页上有类似下图的图标,但在资源里却找不到对应的文件,这是因为这些网页使用了图标库.这里介绍一种常见的图标库——FontAwesome的使用. 1.登录F ...
- 【学习笔记】【Design idea】二、产品内测、公测、候选版本的概念及版本代码的书写
一.前言 参考:百度百科 https://baike.baidu.com/item/beta/640969?fr=aladdin 广义上对测试有着三个传统的称呼:Alpha(α).Beta(β)和Ga ...
- 'module' object has no attribute 'Thread'解决方法及模块加载顺序
源码片段: class myThread(threading.Thread): def __init__(self, threadID, name, counter): threading.Threa ...
- AI - TensorFlow - 示例01:基本分类
基本分类 基本分类(Basic classification):https://www.tensorflow.org/tutorials/keras/basic_classification Fash ...
- 【Android Studio安装部署系列】四十、Android Studio安装Statistic插件(统计项目总行数)
版权声明:本文为HaiyuKing原创文章,转载请注明出处! 概述 Android Studio 是没有提提供统计代码全部行数的功能的,但是对于开发者来说,这个功能确实必备的,Statistic统计代 ...
- SnackbarUtilDemo【Snackbar的封装类】
版权声明:本文为HaiyuKing原创文章,转载请注明出处! 前言 这个工具类参考的是<没时间解释了,快使用Snackbar!——Android Snackbar花式使用指南>,代码几乎一 ...
- KnockoutJS-模板绑定
对于knockoutJS来讲,模板绑定和Mapping插件绑定是十分重要的功能,虽然模板绑定在我工作中用的及其少,但模板绑定的重要性不可忽视,在其他前端框架中,如Angular.Vue等等,模板存在的 ...
- Springboot整合Elastic-Job
Elastic-Job是当当网的任务调度开源框架,有以下功能 分布式调度协调 弹性扩容缩容 失效转移 错过执行作业重触发 作业分片一致性,保证同一分片在分布式环境中仅一个执行实例 自诊断并修复分布式不 ...
- 强化学习(九)Deep Q-Learning进阶之Nature DQN
在强化学习(八)价值函数的近似表示与Deep Q-Learning中,我们讲到了Deep Q-Learning(NIPS 2013)的算法和代码,在这个算法基础上,有很多Deep Q-Learning ...