log4j 新建日志 重启_ASP.NET+MVC+使用+Log4net+记录日志笔记

381f6247bd405494615393f65f506d12.png

前言:

记录系统中的日志,是一个好的项目产品必备的一个环节。每一个产品最终的目的都是要交予客户使用,因为程序员代码的开发水平参差不齐,Bug就成为了项目运维成本最大的因素之一。如何降低项目运维的成本呢,最重要的是要缩短开发人员在系统运维排查问题的时间成本。如果你的系统中很好的集成了日志框架。那么你可以更快更高效的定位问题、解决问题。从而降低系统运维的时间成本。今天小编给大家介绍Log4net日志框架如何在项目中 使用,希望能对大家有所帮助。

Log4net 介绍

1、Log4net 是什么?

Log4net 是 Apache 旗下一个开源的日志框架的项目,它是Log4j 的一个复制版。Log4net中定义了多种日志信息输出模式。它可以根据需要将日志输出到控制台、文本文件、windows 日志事件查看器中、括数据库,邮件发送,以便我们可以根据日志快速定位线上系统的问题。

2、Log4net 日志等级

从高到底分别为:OFF > FATAL > ERROR > WARN > INFO > DEBUG > ALL

二、ASP.NET MVC 使用 Log4net 示例

2.1 如何安装 Log4net Log4net

  1. 使用Nuget 安装 Log4net(工具-NuGet包管理器-程序包管理器控制台(N))
0f4c3299a2b40e34a372741b190ce5fa.png
  1. 使用管理NuGet程序包功能找到Log4net进行安装。
f5c548093e4cef007d70334f06745300.png

2.2 创建 log4net.config 配置文件 ,并且将该文件的属性“复制到输出目录”修改为 “始终复制。

3143d0f34367d3a474ca930786c3489d.png

log4net.config内容如下:

<?xml version="1.0" encoding="utf-8" ?><?xml version="1.0" encoding="utf-8" ?>

2.3 新建LogHelper.cs通用日志类

2ffb3adc7333afb8b49dc8c7e9971cfc.png

代码如下:

public class LogHelper    {        private ILog _log4Net = null;        private const string DEFAULT_LOGGER_NAME = "Logger";        ///         /// Prevents a default instance of the  class from being created.        ///         /// The log4net instance to be used.        private LogHelper(ILog log4NetInstance)        {            _log4Net = log4NetInstance;        }        ///         /// Gets a logger with the specified configuration name.        ///         /// Name of the logger in the configuration.        /// The logger obtained.        /// Thrown when no logger with the specified configuration name was found.        public static LogHelper GetLogger(string configName)        {            var logger = LogManager.GetLogger(configName);            if (logger == null)            {                throw new ArgumentException(string.Format("No logger configuration named '{0}' was found in the configuration.", configName), "configName");            }            return new LogHelper(logger);        }        ///         /// Gets the default.        ///         public static LogHelper Default        {            get            {                return GetLogger(DEFAULT_LOGGER_NAME);            }        }        ///         /// Writes an information level logging message.        ///         /// The message to be written.        public void WriteInfo(object message)        {            _log4Net.Info(message);        }        ///         /// Writes a warning level logging message.        ///         /// The message to be written.        public void WriteWarning(object message)        {            _log4Net.Warn(message);        }        ///         /// Writes a warning level logging message.        ///         /// The message to be written.        /// The exception.        public void WriteWarning(object message, System.Exception exception)        {            _log4Net.Warn(message, exception);        }        ///         /// Writes the error.        ///         /// The message to be written.        public void WriteError(object message)        {            _log4Net.Error(message);        }        ///         /// Writes the error level logging message..        ///         /// The message to be written.        /// The exception.        public void WriteError(object message, System.Exception exception)        {            _log4Net.Error(message, exception);        }        ///         /// Writes the fatal error level logging message..        ///         /// The message to be written.        public void WriteFatal(object message)        {            _log4Net.Fatal(message);        }        ///         /// Writes the fatal error level logging message..        ///         /// The message to be written.        /// The exception.        public void WriteFatal(object message, System.Exception exception)        {            _log4Net.Fatal(message, exception);        }        public void DeleteLog()        {            string logDirPath = Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), "Log");            if (!Directory.Exists(logDirPath)) return;            int days = 30;            foreach (string filePath in Directory.GetFiles(logDirPath))            {                DateTime dt;                DateTime.TryParse(Path.GetFileNameWithoutExtension(filePath).Replace(@"Log", "").Replace(".", "-"), out dt);                if (dt.AddDays(days).CompareTo(DateTime.Now) < 0)                {                    File.Delete(filePath);                }            }        }    }

2.4 AssemblyInfo.cs 文件配置log4net.config

特别注意:针对为web项目要加载web项目对应的AssemblyInfo.cs文件中去,这一点很关键要不然就不能输出日志文件

[assembly: log4net.Config.XmlConfigurator(Watch = true, ConfigFileExtension = "config", ConfigFile = @"Configslog4net.config")]
dac3d2bd3ffe0bac2163c51dbca03264.png

2.5 自定义日志异常处理文件:MyExceptionFileAttribute.cs

用来处理异常记录日志文件,然后可以指定错误的跳转页面。

public override void OnException(ExceptionContext filterContext) {            base.OnException(filterContext);                   if (!string.IsNullOrWhiteSpace(filterContext.Exception.StackTrace))            {                LogHelper.Default.WriteError(filterContext.Exception.StackTrace);            }                //页面跳转到错误页面                        filterContext.HttpContext.Response.Redirect("/Error");        }

2.6 Global.asax新增Log4Net的配置信息

Application_Start.cs 方法加入下面两行代码:

 // 注册log4net  log4net.Config.XmlConfigurator.Configure();  // 注册异常日志文件  GlobalFilters.Filters.Add(new MyExceptionFileAttribute());

测试用法

LoginController.cs 代码加一个异常

    public ActionResult Index()        {            int a = 0;            int b = 6 / a;            return View();        }

效果展示:

28a513693ef6e10c6a4ac3bf2a8a3024.png

结语

本文主要简单介绍ASP.NET MVC 使用 Log4net 的过程。具体的一些用法大家也可以互相交流,比如:如何错误日志如何发邮件、数据库的方式存储、日志文件异步存储等等。后续小编会继续更新相关内容和大家一起学习交流。

个人博客网站:https://programmerblog.xyz

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值