Log4net Series One: log4net construction text Format output

Source: Internet
Author: User
Tags log4net

log4net IntroductionObjective

Project development, record the project log is necessary, if not to say the importance of the log (log can be seen as, the Aircraft's black box, or car driving recorder), according to the level of record, convenient for us to troubleshoot related issues, later project operations, but also a lot of convenience. Basically we enter a company, the development of what you are engaged in, the Company's product or project framework has been set up, we have time to revise, according to the business extension framework, logging is basically our own to call the method of Encapsulation. Today we will study log4net,log4net can do: 1, the mailbox to send logs, 2, record to the database; 3. Generate a notepad file. This chapter Log4net learning, thought to be behind, I will simply a micro-service framework to Prepare. Today we mainly send logs to the mailbox, producing two ways to study Notepad Files. Later there was time for us to save to the database in the Study.

log4net Configuration

Development Environment: VS2013, Create a WEBAPI simulation project scenario to parse Log4net

Create Webapi Step We do a brief description, the following framework directory, today we mainly configure Log4net to parse, so only need to focus on WEBAPI and Webapicommon on the line, here do not forget the three layer between the reference, Webapi need to reference Webapicommon class library

the first step , WebAPI and Webapicommon with NuGet search log4net add: log4net Reference

Second , we add a log4net.config configuration file in webapi, which mainly puts our log configuration information

the Third part , in the new log4net.config configuration file, Add the log configuration, here we do two parts (text format, e-mail), today mainly on the text format, the mailbox configuration We do a separate module;

The following is an example of error, the specific parsing of each line configuration::

<log4net> <!--error log::: log error logs--<!--split log files by date One--<!--appender defines how the log is output writes the log as a rollback file to the text Components. -<appender name="Errorappender"Type="Log4net. Appender.rollingfileappender"> <!--save path: automatically creates a log, logerror file, and <file value= in C drive when the following path project starts"c:\\log\\logerror\\"/>
<!--if you want to add a path to this project, simply remove c:\\ only set Log\\logerror project startup by default create File--<appendtofile value="true"/> <!--how to generate multiple log files (date [dates], file size [size], mix [Composite])--<rollingstyle value="Date"/> <!--this is a date-based folder--<datepattern value="yyyy\\yyyymm\\yyyymmdd '. txt '"/> <!--write to only one file--<staticlogfilename value="false"/> <!--the number of retained log files is automatically deleted before it is removed, as if the value is set only when split by size value="-1"is an unlimited number of Files--<param name="maxsizerollbackups"Value=" -"/> <!--the size of each file. Use only in mixed mode and file size Mode. After the size is exceeded, the positive integer is automatically renamed after all file names, and the oldest write of the number is the Largest. Available Units: kb| mb| GB. Do not use decimals, otherwise it will always be written to the current log--<maximumfilesize value="1GB"/> <!--layout Control the output format of the appender, or it can be XML a appender can only be a layout--> <layout type="Log4net. Layout.patternlayout"> <!--text description at the end of each log-<!--output format Template-<!--<param name="Conversionpattern"Value="recording time:%date thread id:[%thread] log level:%-5level record Class:%loggerOperator id:%property{operator} Operation type:%property{action}%n Current machine name:%property%n current machine name and login user:%username%N Record location:%location%n message description:%property{message}%n exception:%exception%n message:%message%newline%n%n"/>--><!--examples: --Geneva- - -: the: +,111[Ten] INFO Log4netdemo.mainclass [(NULL)]-info--> <!--<conversionpattern value="%newline%n recording time:%date%n thread id:[%thread]%n log level:%-5level%n error description:%message%newline %n"/>--> <conversionpattern value="%n==========%n "log level"%-5level%n "recording time"%Date%n "thread number" [%thread]%n "execution time" [%r] milliseconds%n "error file"%F%n "error Line number"%L%n "class in Error"%logger property [%property{ndc}]%n "error description"%message%n "error Details"%newline"/></layout> </appender> <!--error log::: error Log--<logger name="Logerror"> <level value="ERROR"/> <appender-ref ref="Errorappender"/> </logger> </log4net>

Fourth : Add the Loghelper class in the Webapicommon class library, the class is to get configuration class configuration, send error message, can be reused directly;

[assembly:log4net. Config.xmlconfigurator (configfileextension = "log4net", Watch = true)]namespacewebapicommon{
Public help class for logs public classLoghelper {#region /// <summary> /// /// </summary> /// <param name= "msg" ></param> public Static voidErrorlog (ObjectMsg) {log4net. ILog Log= Log4net. Logmanager.getlogger ("Logerror"); Task.run (()= = Log. Error (msg));//Asynchronous//Task.Factory.StartNew (() =>log. Error (msg));//this type of asynchronous can also
Log. Error (msg); This also works as you need, the better the performance, the stronger, I still use the asynchronous way
        }        /// <summary>        ///         /// </summary>        /// <param name= "ex" ></param>         public Static voiderrorlog (Exception Ex) {log4net. ILog Log= Log4net. Logmanager.getlogger ("Logerror"); Task.run (()= = Log. Error (ex. Message.tostring () +"/r/n"+ Ex. Source.tostring () +"/r/n"+ Ex. Targetsite.tostring () +"/r/n"+Ex.        Stacktrace.tostring ())); }        /// <summary>        ///         /// </summary>        /// <param name= "msg" ></param>        /// <param name= "ex" ></param>         public Static voidErrorlog (Objectmsg, Exception Ex) {log4net. ILog Log= Log4net. Logmanager.getlogger ("Logerror"); if(ex! =NULL) {task.run ()= = Log. Error (msg, ex));//Asynchronous            }            Else{task.run ()= = Log. Error (msg));//Asynchronous            }        }        #endregion    }}

View the background code you will find that the error example has two methods, two ways to pass the parameters, our package above is also based on our business needs, to expand the package

Method Analytic focus::

the Logmanager class, which is used to manage all logger. its GetLogger static method can get the logger in the configuration file

  Log4net. ILog log = Log4net. Logmanager.getlogger ("logerror");  
   This method can also be written in public and then used directly

Static ReadOnly Log4net. ILog Loginfo = Log4net. Logmanager.getlogger ("loginfo");
Static ReadOnly Log4net. ILog Logerror = Log4net. Logmanager.getlogger ("logerror");

Let's introduce a word in the article

[assembly:log4net. Config.xmlconfigurator (configfileextension = "log4net", Watch = true)] Let's read it.

first, Let's start with log4net. Config.xmlconifguratorattribute

Xmlconfiguratorattribute has 3 properties: configfile: the name of the configuration file, the file path relative to the application directory (AppDomain.CurrentDomain.BaseDirectory). The ConfigFile property cannot be used with the Configfileextension Property. Configfileextension: the extension of the configuration file, the file path relative to the Application's directory. The Configfileextension property cannot be used with the ConfigFile Property. Watch: If you set the Watch property to true, the configuration file is Monitored. When the configuration file changes, it reloads. If both ConfigFile and configfileextension are not set, the Application's configuration file, app. config, is Used.

The following statements can be added to the Project's AssemblyInfo.cs file, which can be copied and pasted according to the configuration in the configuration business project:

 //Monitor the default configuration file, App.exe.config[assembly:log4net. Config.xmlconfigurator (Watch=true)]//Monitoring Configuration files, App.exe.log4net. [assembly:log4net. Config.xmlconfigurator (configfileextension="log4net", Watch =true)]//use configuration file log4net.config to not monitor Changes. Note the directory of the Log4net.config files, the BS program in the Site Directory//, CS is in the application startup directory, such as debugging, under/bin/debug, the file properties of the file output directory is generally tuned to//always copy[assembly:log4net. Config.xmlconfigurator (configfile="Log4net.config")]//use configuration file log4net.config, do not monitor changes[assembly:log4net. Config.xmlconfigurator ()]

Fifth : We only use the Webapi test, also need to start the project log

Found in Webapi: global file

The Global.asax file is the central point of an asp. It provides countless events to handle different application-level tasks, such as user authentication, application startup, and processing of user Sessions. You should familiarize yourself with this optional file so that you can build a robust asp.

  protected voidApplication_Start () {arearegistration.registerallareas ();            Globalconfiguration.configure (webapiconfig.register);            Filterconfig.registerglobalfilters (globalfilters.filters);            Routeconfig.registerroutes (routetable.routes); Bundleconfig.registerbundles (bundletable.bundles);

//Startup Item Logging//If you do not want to write the lognet configuration file in Web. config, You can also specify it manually. Log4net. Config.XmlConfigurator.ConfigureAndWatch (NewFileInfo (server.mappath ("/log4net.config"))); } /// <summary> ///Write log through Lognet when program error occurs/// </summary> /// <param name= "sender" ></param> /// <param name= "e" ></param> protected voidapplication_error (Object sender, EventArgs e) {Exception objexp=HttpContext.Current.Server.GetLastError (); Loghelper.errorlog ("\ r \ n Client ip:"+ request.userhostaddress +"\ r \ n Error address:"+Request.url+"\ r \ n Exception information:"+Server.GetLastError (). Message, objexp); }
Method Parsing: application_error, The method I personally recommend to add, if your project where the process is an error, we can catch the exception Information.

The final step: we test, where you need to refer to the Webapicommon class library,
join in where you need to be
Loghelper.errorlog (object);
 public BOOL Add (Department Department)        {            try            {                return  dep.} Add (department);            }             Catch (Exception Ex)            {                Loghelper.errorlog (ex);  Where you need to be   loghelper.errorlog (ex)
Throw
} }
View Results: The C drive creates the file I configured by default,

follow::: year----month-----create

The text records show that we define ourselves in the configuration file,

  Log4net Notepad logging, to the end of the now, the novice on the road, if there is an incorrect description of the place, also please advise!!!
Next: we mainly introduce log4net in the mailbox to send log files, are staying up in the car .....
    • Bo Master is the use of reading, reference, quoting, copying, Copying and pasting a variety of ways to make their own pure 24k article, please forgive bloggers become a shameless document porter!
    • Younger brother just entered the blog writing, the text if there is not, Welcome to use the board to straighten, hope to help You.

Log4net Series One: log4net construction text Format output

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.