Simple Application of lo4net and simple application of lo4net

Source: Internet
Author: User
Tags log4net

Simple Application of lo4net and simple application of lo4net

Log4net introduction:

The log4net library is implemented by the Apache log4j framework on the Microsoft. NET platform. It is a tool that helps programmers output log information to various targets (such as the console, files, and databases.
Log4net logs are very powerful. It can divide logs into different levels and output them to different media in different formats. The following describes how to use log4net in Visual Studio2013 to quickly create system logs and how to expand to output custom fields.

1. Create a log4net_test_01 console application> right-click Project> Manage NuGet package> enter log4> install Apache log4net

2. Add the log4net. config file to the project, set the file property to copy to the output directory to always copy, and add the following configuration items in it:

<? Xml version = "1.0" encoding = "UTF-8"?> <Configuration> <configSections> <section name = "log4net" type = "log4net. Config. Log4NetConfigurationSectionHandler, log4net"/> </configSections> <log4net> <! -- Record normal logs --> <logger name = "logerror"> <! -- (High) OFF> FATAL> ERROR> WARN> INFO> DEBUG> ALL (low) --> <level value = "ALL"/> <appender-ref = "ErrorAppender"/> </logger> <appender name = "InfoAppender" type = "log4net. appender. rollingFileAppender "> <! -- Log Path --> <param name = "File" value = "./App_Log \ Info \ InfoLog. log"/> <! -- Whether to append logs to the file --> <param name = "AppendToFile" value = "true"/> <! -- Log Retention days --> <param name = "MaxSizeRollBackups" value = "100"/> <! -- Log maximum for a single file --> <param name = "MaximumFileSize" value = "1 MB"/> <! -- Scroll logs by Size --> <param name = "RollingStyle" value = "Size"/> <! -- Whether the log file name is fixed --> <param name = "StaticLogFileName" value = "true"/> <layout type = "log4net. layout. patternLayout "> <param name =" ConversionPattern "value =" %-5 p % d [% c] % m % n "/> </layout> </appender> <! -- Record exception logs --> <logger name = "loginfo"> <! -- (High) OFF> FATAL> ERROR> WARN> INFO> DEBUG> ALL (low) --> <level value = "ALL"/> <appender-ref = "InfoAppender"/> </logger> <appender name = "ErrorAppender" type = "log4net. appender. rollingFileAppender "> <! -- Log Path --> <param name = "File" value = "./App_Log \ Error \ ErrorLog. log"/> <! -- Whether to append logs to the file --> <param name = "AppendToFile" value = "true"/> <! -- Log Retention days --> <param name = "MaxSizeRollBackups" value = "100"/> <! -- Log maximum for a single file --> <param name = "MaximumFileSize" value = "1 MB"/> <! -- Scroll logs by Size --> <param name = "RollingStyle" value = "Size"/> <! -- Whether the log file name is fixed --> <param name = "StaticLogFileName" value = "true"/> <layout type = "log4net. layout. patternLayout "> <param name =" ConversionPattern "value =" %-5 p % d [% c] % m % n "/> </layout> </appender> </ log4net> </configuration>

 

3. Use the log to record common logs and exception logs:

Using System; using System. collections. generic; using System. linq; using System. text; using System. threading. tasks; using log4net; using log4net. config; namespace log4net_test_01 {class Program {public static readonly log4net. ILog loginfo = log4net. logManager. getLogger ("loginfo"); public static readonly log4net. ILog logerror = log4net. logManager. getLogger ("logerror"); static void Main (string [] args) {InitLog4Net (); if (loginfo. isInfoEnabled) {loginfo. info ("Write normal operation log");} if (logerror. isInfoEnabled) {logerror. error ("Exception occurred", new Exception ("Exception occurred here");} Console. readLine ();} static void InitLog4Net () {XmlConfigurator. configure (new System. IO. fileInfo (AppDomain. currentDomain. baseDirectory + "log4net. config "); Console. writeLine ("successfully loaded Log4Net ");}}}

4. Check that the App_Log folder is added to the program directory after running, and there are Error and Info folders in it, storing the recorded day files.

5. the same is true for using log4net to record days in MVC projects. Add references to get log4net library files and then add log4net. config configuration file. The difference is that the read configuration is initialized at Global. the Application_Start () method in asax is completed. Note log4net. copy the config file property to the output directory to always copy:

Using System; using System. collections. generic; using System. linq; using System. web; using System. web. mvc; using System. web. routing; using log4net. config; namespace log4net_test02 {public class MvcApplication: System. web. httpApplication {protected void Application_Start () {AreaRegistration. registerAllAreas (); RouteConfig. registerRoutes (RouteTable. routes); // automatically configure the log4net system XmlConfigurator Based on the application configuration. configure (new System. IO. fileInfo (AppDomain. currentDomain. baseDirectory + "log4net. config "));}}}

6. log recording:

Using System; using System. collections. generic; using System. linq; using System. web; using System. web. mvc; namespace log4net_test02.Controllers {public class HomeController: Controller {// GET:/Home/public ActionResult Index () {Write ("record common logs "); write ("record error log", new Exception ("custom Exception"); return Content ("use log4net in web mvc");} public static readonly log4net. ILog loginfo = log4net. logManager. getLogger ("loginfo"); public static readonly log4net. ILog logerror = log4net. logManager. getLogger ("logerror "); /// <summary> /// common file record log /// </summary> /// <param name = "info"> </param> private static void Write (string info) {if (loginfo. isInfoEnabled) {loginfo. info (info );}} /// <summary> // Error Log // </summary> /// <param name = "info"> </param> /// <param name = "se"> </param> private static void Write (string info, exception se) {if (logerror. isErrorEnabled) {logerror. error (info, se );}}}}

Note: The objects and methods for recording common logs and error logs are not independent. In actual project development, they should be encapsulated and used in a unified manner.

 

Related Article

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.