• ASP.NET MVC Web项目中使用Log4Net记录日志,并按照日志类型分文件存储


    1.创建MvcLog4Net项目

    2.创建 空的MVC项目

    3.项目创建完成的效果

    4.选择项目,点击鼠标右键,在弹出菜单中选择“管理解决方案的 NuGet 程序包”

    5.

    在NuGet浏览界面:

    点击“浏览”选项,输入“log4net”,在自动搜索结果中选中第一项,并勾选右侧的项目,点击“安装”按钮

    6.在弹出“预览更改”界面中,点击“确定”按钮

    7.安装完成后,在项目的引用中可以看到 log4net

    8.

    在 Global.asax 文件的 Application_Start 方法中,增加 

    log4net.Config.XmlConfigurator.Configure();

    9.

    在 Web.config 文件中的 configuration 节点下面增加(必须紧挨着configuration 节点添加)

      <configSections>

        <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />

      </configSections>

    10.

    在 Web.config 文件中,添加 log4net 节点,配置日志类别:

      <log4net>

        <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender, log4net">

          <param name="LockingModel" type="log4net.Appender.FileAppender+MinimalLock" />

          <param name="File" value="Log/Log/" />

          <param name="StaticLogFileName" value="false" />

          <param name="DatePattern" value="yyyy-MM-dd.'log'" />

          <param name="AppendToFile" value="true" />

          <param name="MaxSizeRollBackups" value="-1" />

          <param name="MaximumFileSize" value="20MB" />

          <param name="RollingStyle" value="Date" />

          <layout type="log4net.Layout.PatternLayout">

            <param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n%newline" />

          </layout>

        </appender>

        <appender name="RollingLogFileErrorAppender" type="log4net.Appender.RollingFileAppender, log4net">

          <param name="LockingModel" type="log4net.Appender.FileAppender+MinimalLock" />

          <param name="File" value="Log/ErrorLog/" />

          <param name="StaticLogFileName" value="false" />

          <param name="DatePattern" value="yyyy-MM-dd.'log'" />

          <param name="AppendToFile" value="true" />

          <param name="MaxSizeRollBackups" value="-1" />

          <param name="MaximumFileSize" value="10MB" />

          <param name="RollingStyle" value="Date" />

          <layout type="log4net.Layout.PatternLayout">

            <param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n%newline" />

          </layout>

          <filter type="log4net.Filter.LevelRangeFilter">

            <levelMin value="WARN" />

            <levelMax value="FATAL" />

          </filter>

        </appender>

        <root>

          <!--控制级别,由低到高: ALL|DEBUG|INFO|WARN|ERROR|FATAL|OFF-->

          <!--比如定义级别为INFO,则INFO级别向下的级别,比如DEBUG日志将不会被记录-->

          <!--如果没有定义LEVEL的值,则缺省为DEBUG-->

          <level value="ALL" />

          <appender-ref ref="RollingLogFileAppender" />

          <appender-ref ref="RollingLogFileErrorAppender" />

        </root>

      </log4net>

    11.Web.config中添加完log4net后的效果

    12.在项目的 Controller 文件夹,右键添加 控制器

    13.在弹出添加控制器界面,选择 “MVC控制器 - 空”

    14.输入控制器名字 HomeController,点击 “添加”按钮

    15.在HomeController的Index Action中右键,选择“添加视图”

    16.在弹出“添加视图”界面,点击“添加”按钮

    17.

    在Index视图中写入测试日志:

     log4net.ILog log = log4net.LogManager.GetLogger(typeof(HomeController));

                log.Info("这个是 Info Level 的日志!");

                log.Error("这个是 Error Level 的日志!");

    18.最终日志效果

    配置文件:

    <?xml version="1.0" encoding="utf-8"?>
    <!--
      For more information on how to configure your ASP.NET application, please visit
      http://go.microsoft.com/fwlink/?LinkId=169433
      -->
    
    <configuration>
    	<configSections>
    		<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
    	</configSections>
    	<appSettings>
        <add key="webpages:Version" value="2.0.0.0" />
        <add key="webpages:Enabled" value="false" />
        <add key="PreserveLoginUrl" value="true" />
        <add key="ClientValidationEnabled" value="true" />
        <add key="UnobtrusiveJavaScriptEnabled" value="true" />
      </appSettings>
      <system.web>
        
        <httpRuntime targetFramework="4.5" />
        
        <compilation debug="true" targetFramework="4.5" />
    
        <pages>
          <namespaces>
            <add namespace="System.Web.Helpers" />
            <add namespace="System.Web.Mvc" />
            <add namespace="System.Web.Mvc.Ajax" />
            <add namespace="System.Web.Mvc.Html" />
            <add namespace="System.Web.Routing" />
            <add namespace="System.Web.WebPages" />
          </namespaces>
        </pages>
      </system.web>
      <system.webServer>
        <validation validateIntegratedModeConfiguration="false" />
         
      <handlers>
          <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
          <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
          <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
          <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%Microsoft.NETFrameworkv4.0.30319aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
          <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%Microsoft.NETFramework64v4.0.30319aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
          <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
        </handlers></system.webServer>
    
    	<log4net>
    		<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender, log4net">
    
    			<param name="LockingModel" type="log4net.Appender.FileAppender+MinimalLock" />
    
    			<param name="File" value="Log/Log/" />
    
    			<param name="StaticLogFileName" value="false" />
    
    			<param name="DatePattern" value="yyyy-MM-dd.'log'" />
    
    			<param name="AppendToFile" value="true" />
    
    			<param name="MaxSizeRollBackups" value="-1" />
    
    			<param name="MaximumFileSize" value="20MB" />
    
    			<param name="RollingStyle" value="Date" />
    
    			<layout type="log4net.Layout.PatternLayout">
    				<param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n%newline" />
    			</layout>
    		</appender>
    		<appender name="RollingLogFileErrorAppender" type="log4net.Appender.RollingFileAppender, log4net">
    
    			<param name="LockingModel" type="log4net.Appender.FileAppender+MinimalLock" />
    
    			<param name="File" value="Log/ErrorLog/" />
    
    			<param name="StaticLogFileName" value="false" />
    
    			<param name="DatePattern" value="yyyy-MM-dd.'log'" />
    
    			<param name="AppendToFile" value="true" />
    
    			<param name="MaxSizeRollBackups" value="-1" />
    
    			<param name="MaximumFileSize" value="10MB" />
    
    			<param name="RollingStyle" value="Date" />
    
    			<layout type="log4net.Layout.PatternLayout">
    				<param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n%newline" />
    			</layout>
    
    			<filter type="log4net.Filter.LevelRangeFilter">
    				<levelMin value="WARN" />
    				<levelMax value="FATAL" />
    			</filter>
    		</appender>
    		<root>
    			<!--控制级别,由低到高: ALL|DEBUG|INFO|WARN|ERROR|FATAL|OFF-->
    
    			<!--比如定义级别为INFO,则INFO级别向下的级别,比如DEBUG日志将不会被记录-->
    
    			<!--如果没有定义LEVEL的值,则缺省为DEBUG-->
    
    			<level value="ALL" />
    			<appender-ref ref="RollingLogFileAppender" />
    			<appender-ref ref="RollingLogFileErrorAppender" />
    		</root>
    	</log4net>
    </configuration>
    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Http;
    using System.Web.Mvc;
    using System.Web.Routing;
    
    namespace MvcLog4Net
    {
        // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
        // visit http://go.microsoft.com/?LinkId=9394801
        public class MvcApplication : System.Web.HttpApplication
        {
            protected void Application_Start()
            {
                AreaRegistration.RegisterAllAreas();
    
                WebApiConfig.Register(GlobalConfiguration.Configuration);
                FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
                RouteConfig.RegisterRoutes(RouteTable.Routes);
                log4net.Config.XmlConfigurator.Configure();
            }
        }
    }
    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    
    namespace MvcLog4Net.Controllers
    {
        public class HomeController : Controller
        {
            //
            // GET: /Home/
    
            public ActionResult Index()
            {
    
                log4net.ILog log = log4net.LogManager.GetLogger(typeof(HomeController));
    
                log.Info("这个是 Info Level 的日志!");
    
                log.Error("这个是 Error Level 的日志!");
    
                return View();
            }
    
        }
    }

    来源:https://jingyan.baidu.com/album/7e4409530087222fc0e2ef99.html?picindex=1

     
     
  • 相关阅读:
    golang fmt用法举例
    golang init函数
    golang 定时器
    golang 如何判断变量的类型
    题目:IO多路复用版FTP
    Python模块——gevent 在协程学习中遇到的模块
    python入门三十二天——协程 异步IO数据库队列缓存
    java——第一天 变量,java的基础类型
    操作PPT模块 python-pptx
    python入门三十一天---多进程
  • 原文地址:https://www.cnblogs.com/sxjljj/p/9850810.html
Copyright © 2020-2023  润新知