How to record complete log information using the Log4net custom property configuration feature

Source: Internet
Author: User
Tags log4net

Log4net as a professional log record control, for its powerful features we must not be unfamiliar. I'll explain in more detail how to take advantage of its custom properties to make the log information more complete.

First, to create a test project, the Log4net component can be downloaded from the web itself, or it can be installed through NuGet.

Second, create the log model and database table, because our log information can be output as text, or output to the database.




Third, add the Mylayout,mypatternconverter class extension patternlayout.



Four, add the Log4net.config file, the input method is defined.

<?xml version= "1.0" encoding= "Utf-8"?>
<configuration>
<configSections>
<section name= "log4net" type= "log4net. Config.log4netconfigurationsectionhandler,log4net "/>
</configSections>
<log4net>
<!--conversionpattern explanation
%M (message): Output log message, such as Ilog.debug (...) A message for the output
%n (New line): Swap
%d (datetime): Outputs the moment at which the current statement runs
%r (Run time): The number of milliseconds that the output program consumes from running to executing to the current statement
%T (thread ID): The thread ID where the current statement is located
%p: The current priority level of the log, which is debug, INFO, WARN ... such as
%c (Class): The name of the current log object
%l: The line number where the output statement is located
%F: The file name where the output statement resides
%-Number: Indicates the minimum length of the item and, if not enough, fills it with a space
-

<!--definition output to the console command line--
<logger name= "MyLogger" >
<level value= "All"/>
<appender-ref ref= "Consoleappender"/>
</logger>

<!--definition output to the console command line--
<appender name= "Consoleappender" type= "log4net. Appender.consoleappender ">
<layout type= "Log4nettest.mylayout" >
<param name= "Conversionpattern" value= "Log time:%d%n log level:%-5p%n user Id:%property{userid}%n user name:%property{username}% N Log information:%property{message}%n Exception information:%exception%n%n "/>
</layout>
</appender>

<!--define output to Windows events--
<appender name= "Windowsappender" type= "log4net. Appender.eventlogappender ">
<layout type= "Log4nettest.mylayout" >
<param name= "Conversionpattern" value= "Log time:%d%n log level:%-5p%n user Id:%property{userid}%n user name:%property{username}% N Log information:%property{message}%n Exception information:%exception%n%n "/>
</layout>
</appender>

<!--definition output to file--
<appender name= "Textappender" type= "log4net. Appender.rollingfileappender ">
<param name= "File" value= "log\\"/>
<param name= "Appendtofile" value= "true"/>
<param name= "MaxFileSize" value= "10240"/>
<param name= "maxsizerollbackups" value= "/>"
<param name= "Staticlogfilename" value= "false"/>
<param name= "Datepattern" value= "YyyyMMdd"/>
<param name= "Rollingstyle" value= "Date"/>
<layout type= "Log4nettest.mylayout" >
<param name= "Conversionpattern" value= "Log time:%d%n log level:%-5p%n user Id:%property{userid}%n user name:%property{username}% N Log information:%property{message}%n Exception information:%exception%n%n "/>
</layout>
</appender>

<!--define output to database--
<appender name= "Databaseappender" type= "log4net. Appender.adonetappender ">
<!--log cache write number of bars--
<buffersize value= "1"/>
<!--log Database connection string--
<connectiontype value= "System.Data.SqlClient.SqlConnection, System.Data, version=1.0.3300.0, Culture=neutral, publickeytoken=b77a5c561934e089 "/>
<connectionstring value= "Data source=.\sql2008;initial catalog=demo;integrated security=false;persist security Info=true; User Id=sa; Password=1qaz "/>
<!--log Database Scripts--
<commandtext value= "INSERT into Loginfo ([logdate],[loglevel],[userid],[username],[message],[exception]) VALUES ( @LogDate, @LogLevel, @UserId, @UserName, @Message, @Exception) "/>
<!--log Time Logdate--
<parameter>
<parametername value= "@LogDate"/>
<dbtype value= "String"/>
<size value= "/>"
<layout type= "log4net. Layout.patternlayout ">
<conversionpattern value= "%date{yyyy-mm-dd HH:mm:ss}"/>
</layout>
</parameter>
<!--log type loglevel--
<parameter>
<parametername value= "@LogLevel"/>
<dbtype value= "String"/>
<size value= "Ten"/>
<layout type= "log4net. Layout.patternlayout ">
<conversionpattern value= "%level"/>
</layout>
</parameter>
<!--custom UserID--
<parameter>
<parametername value= "@UserId"/>
<dbtype value= "String"/>
<size value= "/>"
<layout type= "Log4nettest.mylayout" >
<conversionpattern value= "%property{userid}"/>
</layout>
</parameter>
<!--custom Username--
<parameter>
<parametername value= "@UserName"/>
<dbtype value= "String"/>
<size value= "/>"
<layout type= "Log4nettest.mylayout" >
<conversionpattern value= "%property{username}"/>
</layout>
</parameter>
<!--custom Message--
<parameter>
<parametername value= "@Message"/>
<dbtype value= "String"/>
<size value= "/>"
<layout type= "Log4nettest.mylayout" >
<conversionpattern value= "%property{message}"/>
</layout>
</parameter>
<!--exception Information exception--
<parameter>
<parametername value= "@Exception"/>
<dbtype value= "String"/>
<size value= "4000"/>
<layout type= "log4net. Layout.exceptionlayout "/>
</parameter>
</appender>
</log4net>
</configuration>

Five, add the LogHelper.cs class for the write operation of the respective information.

Using System;
Using System.Diagnostics;
Using System.IO;
Using System.Windows.Forms;
Using Log4net;
[Assembly:log4net. Config.xmlconfigurator (Watch = True)]

Namespace Log4nettest
{
public class Loghelper
{
<summary>
Loggername
</summary>
public static string loggername = String. Empty;
<summary>
User ID
</summary>
public static string UserID = String. Empty;
<summary>
User name
</summary>
public static string UserName = String. Empty;

private static ILog ILog;
private static logentity logentity;

<summary>
Interface
</summary>
private static ILog Log
{
Get
{
String path = Application.startuppath + @ "\log4net.config";
Log4net. Config.XmlConfigurator.Configure (new FileInfo (path));

if (ILog = = null)
{
ILog = log4net. Logmanager.getlogger (Loggername);
}
Else
{
if (iLog.Logger.Name! = loggername)
{
ILog = log4net. Logmanager.getlogger (Loggername);
}
}

return iLog;
}
}

<summary>
Constructing message Entities
</summary>
<param name= "Message" ></param>
<returns></returns>
private static logentity Buildmessagemode (String message)
{
if (logentity = = null)
{
logentity = new Logentity ();
Logentity.userid = UserID;
Logentity.username = UserName;
Logentity.message = Message;
}
Else
Logentity.message = Message;

return logentity;
}

<summary>
Debugging
</summary>
<param name= "message" > Messages </param>
public static void Debug (String message)
{
if (log. isdebugenabled)
Log. Debug (Buildmessagemode (message));
}

<summary>
Debugging
</summary>
<param name= "message" > Messages </param>
<param name= "Exception" > Anomalies </param>
public static void Debug (String message, Exception ex)
{
if (log. isdebugenabled)
Log. Debug (Buildmessagemode (message), ex);
}

<summary>
Information
</summary>
<param name= "message" > Messages </param>
public static void Info (String message)
{
if (log. isinfoenabled)
Log. Info (Buildmessagemode (message));
}

<summary>
Information
</summary>
<param name= "message" > Messages </param>
<param name= "Exception" > Anomalies </param>
public static void Info (String message, Exception ex)
{
if (log. isinfoenabled)
Log. Info (Buildmessagemode (message), ex);
}

<summary>
General error
</summary>
<param name= "message" > Messages </param>
public static void Error (String message)
{
if (log. iserrorenabled)
Log. Error (Buildmessagemode (message));
}

<summary>
General error
</summary>
<param name= "message" > Messages </param>
<param name= "Exception" > Anomalies </param>
public static void Error (String message, Exception Exception)
{
if (log. iserrorenabled)
Log. Error (Buildmessagemode (message), exception);
}

<summary>
Warning
</summary>
<param name= "message" > Messages </param>
public static void Warn (String message)
{
if (log. iswarnenabled)
Log. Warn (Buildmessagemode (message));
}

<summary>
Warning
</summary>
<param name= "message" > Messages </param>
<param name= "Exception" > Anomalies </param>
public static void Warn (String message, Exception ex)
{
if (log. iswarnenabled)
Log. Warn (Buildmessagemode (message), ex);
}

<summary>
Serious
</summary>
<param name= "message" > Messages </param>
public static void Fatal (String message)
{
if (log. isfatalenabled)
Log. Fatal (Buildmessagemode (message));
}

<summary>
Serious
</summary>
<param name= "message" > Messages </param>
<param name= "Exception" > Anomalies </param>
public static void Fatal (String message, Exception ex)
{
if (log. isfatalenabled)
Log. Fatal (Buildmessagemode (message), ex);
}
}
}

Six, the log effect test, as long as by modifying the log4net.config, you can achieve various ways of input.


Output to the console:

<logger name= "MyLogger" >
<level value= "All"/>
<appender-ref ref= "Consoleappender"/>
</logger>




Output to File:

<logger name= "MyLogger" >
<level value= "All"/>
<appender-ref ref= "Textappender"/>
</logger>





Output to database:
<logger name= "MyLogger" >
<level value= "All"/>
<appender-ref ref= "Databaseappender"/>
</logger>






How to use the Log4net custom property configuration feature to record full log information

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.