Log4net VS2012 Log layout customization, error logs and info logs are recorded in separate files

Source: Internet
Author: User
Tags httpcontext log4net

    • Turn on the "tools" = "NuGet Package Manager" = "NuGet Package for Management solution" menu in VS

    • In the Manage NuGet Packages window, search for log4net and install

    • Sometimes, we need to record some business data in the log, such as operator information, we create a new class Webmethodlog, to hold the information needed in the log
 Public classWebmethodlog { Public stringoperatorno{Get;Set;}  Public stringOperatorname {Get;Set; }  Public stringMethod {Get;Set; }  Public stringMessage {Get;Set; } }

    • New Webmethodpatternconvert Class
  Public classWebmethodpatternconvert:patternlayoutconverter {protected Override voidConvert (TextWriter writer, loggingevent loggingevent) {varWebMethod = Loggingevent.messageobject asWebmethodlog; if(WebMethod = =NULL)return; Writer. Write ("\r\ n------------------------------------------------------------begin------------------------------------------------------- ---------------"); Writer. Write ("\r\ndate:"+system.datetime.now.tostring ("YYYY-MM-DD hh:mm:ss,fff")); Writer. Write (string. Format ("\r\noperator No.: {0}, Operator Name: {1}", Webmethod.operatorno,webmethod.operatorname)); Writer. Write (string. Format ("\r\nmethod: {0}", Webmethod.method)); Writer. Write ("\r\nmessage:"+webmethod.message); Writer. Write ("\r\ N------------------------------------------------------------End--------------------------------------------------------- ----------------"); }     }

    • New Webmethodpatternlayout Class
 Public class webmethodpatternlayout:log4net. Layout.patternlayout      {        public  webmethodpatternlayout ()        }            {this. Addconverter ("webMethod"typeof(Webmethodpatternconvert));        }        } 

    • The following configuration is done in Web. config:

1. Add the following configuration to the Configsections tab

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

2. Add the following configurations under the Configuration tab  

<log4net> <root> <level value=" All"/> <appender-ref ref="Infoappender"/> <appender-ref ref="Errorappender"/> </root> <logger name="Loginfo"> <level value="Info"/> <appender-ref ref="Infoappender"/> </logger> <appender name="Infoappender"Type="log4net. Appender.rollingfileappender,log4net"> <param name="File"Value="logs/"/> <param name="Appendtofile"Value="true"/> <param name="MaxFileSize"Value="10240"/> <param name="maxsizerollbackups"Value=" -"/> <param name="Staticlogfilename"Value="false"/> <param name="Rollingstyle"Value="Date"/> <param name="Datepattern"Value="&quot; logs_&quot;yyyymmddhh&quot;info.txt&quot;"/> <!--<layout type="log4net. Layout.patternlayout,log4net">--> <layout type="HITTS.Web.Common.WebMethodPatternLayout"> <param name="Conversionpattern"Value="%webmethod"/> </layout> <filter type="log4net. Filter.levelrangefilter"> <levelmin value=" All"/> <levelmax value="INFO"/> </filter> </appender> <logger name="LogError"> <level value="Error"/> <appender-ref ref="Errorappender"/> </logger> <appender name="Errorappender"Type="log4net. Appender.rollingfileappender,log4net"> <param name="File"Value="logs/"/> <param name="Appendtofile"Value="true"/> <param name="MaxFileSize"Value="10240"/> <param name="maxsizerollbackups"Value=" -"/> <param name="Staticlogfilename"Value="false"/> <param name="Rollingstyle"Value="Date"/> <param name="Datepattern"Value="&quot; logs_&quot;yyyymmddhh&quot; error.txt&quot;"/> <layout type="HITTS.Web.Common.WebMethodPatternLayout"> <param name="Conversionpattern"Value="%webmethod"/> </layout> <filter type="log4net. Filter.levelrangefilter"> <levelmin value="ERROR"/> <levelmax value="FATAL"/> </filter> </appender> <appender name="ConsoleApp"Type="log4net. Appender.consoleappender,log4net"> <layout type="log4net. Layout.patternlayout,log4net"> <param name="Conversionpattern"Value="%d [%t]%-5p%c-%m%n"/> </layout> </appender> </log4net>

    • Add the following code to the AssemblyInfo.cs file:
" Web. config " true)]

    • Test Log Code
[WebMethod]

public static string Logtest ()
{
Log4net. ILog log = log4net. Logmanager.getlogger ("Infotest");
String json = "{' Name ': ' Cherry ', ' age ': ' 27 '}";
Log. Info (New Webmethodlog () {Operatorno = employee. Employeeno, Operatorname = employee. Name, method = HttpContext.Current.Request.Path, message = json});
Log. Error (New Webmethodlog () {Operatorno = employee. Employeeno, Operatorname = employee. Name, method = HttpContext.Current.Request.Path, message = json});
return JSON;
}

    • The test results are as follows:

The following files are generated under the Logs folder:

Log4net VS2012 Log layout customization, error logs and info logs are recorded in separate files

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.