Log4net.config writes the journal to both the database and the file

Source: Internet
Author: User
Tags log4net

"1"

1. Create a new log4net.config configuration file in the project.

2 "from the Log4net official website under the Log4net package, and then in the package's Bin folder in the Net folder in the 4.0 folder found in the Log4net.dll file, and then bring it into our project to

<?xml version= "1.0" encoding= "Utf-8"?><configuration> <configSections> <!--Configure a node name called log4net-- > <section name= "log4net" type= "log4net. Config.log4netconfigurationsectionhandler, log4net "/> </configSections> <log4net> <!--write to file-- > <appender name= "logfileappender" type= "log4net. Appender.rollingfileappender,log4net "> <!--file path, if Rollingstyle is composite or date, this is set as directory, file name is set in Datepattern , the others will have a file name here. Extended Support for virtual directories--<param name= "File" value= "log\\loginfo\\"/><!--to write the journal to the Loginfo folder below the Log folder below the directory Yyyy-m M-dd.txt file--<param name= "Appendtofile" value= "true"/> <param name= "maxsizerollbackups" Valu E= "/> <param name=" maximumfilesize "value=" 10240KB "/> <param name=" staticlogfilename "value=" f Alse "/> <param name=" Rollingstyle "value=" Date "/> <param name=" Datepattern "value=" Yyyy-M M-dd.txt "/> <!--TXT suffix must be uppercase, noThere is a problem--<param name= "countdirection" value= "-1"/> <!--log4net record the wrong format (i.e.: what format (layout) is used to log errors )--<layout type= "log4net. Layout.patternlayout "> <param name=" conversionpattern "value=" "Time":%d%n "Level":%p%n "class name":%c%n "Thread id":%thread %n "File Address":%F%l line%n "Log content":%m%n "journal detail":%exception% N--------------------------------------------------------------------------------------------------------------- %n "/> </layout> </appender> <!--write a journal to the database--<appender name=" Adonetappender_sqls Erver "Type=" log4net. Appender.adonetappender "> <buffersize value=" 0 "/> <connectiontype value=" System.Data.SqlClient.SqlC Onnection, System.Data, version=1.0.5000.0, culture=neutral, publickeytoken=b77a5c561934e089 "/> <!--<conne Ctionstring value= "Server=fb-vaio;database=sales; Uid=sa; pwd=123456; Connect timeout=15; "/>--> <connectionstring value=" Data source=fb-vaio;initial catalog=Sales;integrated Security=sspi; Connect timeout=15; "/> <commandtext value=" INSERT into Xlog ([date],[thread],[level],[logger],[message],[excep tion]) VALUES (@log_date, @thread, @log_level, @logger, @message, @exception) "/> <parameter> <par Ametername value= "@log_date"/> <dbtype value= "DateTime"/> <layout type= "log4net. Layout.rawtimestamplayout "/> </parameter> <parameter> <parametername value=" @thr EAD "/> <dbtype value=" String "/> <size value=" 255 "/> <layout type=" log4net.      Layout.patternlayout "> <conversionpattern value="%t "/> </layout> </parameter> <parameter> <parametername value= "@log_level"/> <dbtype value= "String"/> <siz E value= "/> <layout type=" log4net. Layout.patternlayout "> <conversionpattern value="%p "/> </layout> </parameter> <parameter> <parametername value= "@logger"/> <dbtype value = "String"/> <size value= "/> <layout type=" log4net. Layout.patternlayout "> <conversionpattern value="%logger "/> </layout> &LT;/PARAMETER&G      T <parameter> <parametername value= "@message"/> <dbtype value= "String"/> <size val ue= "4000"/> <layout type= "log4net.      Layout.patternlayout "> <conversionpattern value="%m "/> </layout> </parameter> <parameter> <parametername value= "@exception"/> <dbtype value= "String"/> <siz E value= "/> <layout type=" log4net. Layout.exceptionlayout "> <conversionpattern value="%exception "/> </layout> </parame Ter> </appender> <!--log errors at what level of error "Note: If you have more than one appender-ref, you shouldPut them under the same root node "-<root> <level value=" All "/> <appender-ref ref=" Logfileappender "/> <appender-ref ref= "Adonetappender_sqlserver"/> </root> </log4net></configuration>
If the project is an WebForm application, you can find the AssemblyInfo.cs class under the properties file under the root directory. Open it and add a piece of code to the last side of the AssemblyInfo.cs class:

configfile= "Log4net.config" means that the path of our configuration file is mylognet4.config This configuration file under the root directory of the Web site, so that when the program runs it will follow this path to read the configuration file//watch: The Log4net framework uses this property to determine if the file changes need to be monitored at runtime, and if this property is true, then Filssystemwatcher will be used to monitor the file changes, rename, delete, and so on. (That is, if the configuration file changes when it adapts to the change, that is, it will automatically read the change, and do not need to restart the running Web application)// In fact, if we log4net configuration files are directly configured in the Web. config file, there is no need to configure it here. The reason why we need to configure this is because we are independent of a log4net configuration file, in order to associate it with our program, here, we need to read the Log4net configuration file we established, loaded into our program [Assembly:log4net. Config.xmlconfigurator (configfile= "Log4net.config", Watch = True)]
What if the project is not a WebForm application, or there is no AssemblyInfo.cs in the project? A: Then we can create a Global.asax file under the project and directory

Add a piece of code in the protected void Application_Start (object sender, EventArgs e) method of the Global.asax file as follows:

protected void Application_Start (object sender, EventArgs e) {    string filePath = Server.MapPath ("~/log4net.config") ;    FileInfo fil = new FileInfo (filePath);    Log4net. Config.XmlConfigurator.Configure (fil); Will//In fact, the above three code can be used in the following sentence instead of    //log4net. Config.XmlConfigurator.Configure (New System.IO.FileInfo (Server.MapPath ("~/log4net.config")); }
Note: The main function of our two-segment code above is to load our new log4net.config configuration file into our project (because our new Log4net.config profile is not related to our project, so it needs to be loaded into our project) if the ASSEMB The LyInfo.cs file is loaded and does not need to be loaded again in the Global.asax file. (depending on the hobby, choose both)


To add the WebForm1.aspx file to the project, we drag a button control to our WebForm1.aspx page, the button control named "Please click the button, test the error"

Double-click the button control, add the clicking event to it, and the code is as follows:

Using system;using system.collections.generic;using system.linq;using system.web;using System.Web.UI;using System.web.ui.webcontrols;using log4net;using system.reflection;namespace webtest{public partial class Webform1:syst Em. Web.UI.Page {protected void Page_Load (object sender, EventArgs e) {} protected void Butto            N1_click (object sender, EventArgs e) {int x = 6;            int y = 0;             try {int z = x/y;                 } catch (Exception ex) {//getlogger () static method to retrieve the existence of a logger object in the frame and create an object with the name logger if it does not exist Log4net. ILog log = log4net. Logmanager.getlogger ("Weblogger");//This weblogger is actually the name attribute of the logger in the configuration file. It represents the wrong class name, Log4net. ILog log = log4net. Logmanager.getlogger (Methodbase.getcurrentmethod (). DECLARINGTYPE);//Gets the wrong class if (log. iserrorenabled) {log. Error ("BUG:" +ex.           MESSAGE,EX);     } Response.Write ("OK"); }        }    }}

Then we create a new table in the data named Xlog table structure as follows:



All right. Now you can see the test results and run our project.


Click the button on the page. Then we look at the data in the Xlog table in our database and find that an error journal has been written to the table.

Let's go to the disk directory where the project is located, under the project folder we see that a log folder is generated, under the log folder there is a Loginfo folder, under the Loginfo folder there is a txt file named after the current date, this file is the error diary we just generated. Open and look at:



Log4net.config writes the journal to both the database and the file

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.