[. NET] Log4net writes operation logs to the database

Source: Internet
Author: User

[. NET] Log4net writes operation logs to the database

For more information about the configuration file, see [. NET] log4net Configuration File Parsing in the previous blog.

Add such a code in Global. aspx to read the configuration file and initialize the log4net environment.

public class Global : System.Web.HttpApplication    {        protected void Application_Start(object sender, EventArgs e)        {            log4net.Config.XmlConfigurator.Configure();        }

Create a new Log folder and create all the classes under the Log under this folder. Make sure that the namespaces of these classes are consistent.

The first LogMessage class.

This class includes custom attributes, that is, all fields to be written to the database, corresponding to the content of the insert statement in the configuration file.

Using System. web; using System. web. sessionState; namespace LogDB {// <summary> // LogMessage summary /// </summary> public class LogMessage: IRequiresSessionState {public LogMessage () {} public LogMessage (string userID, string userName, string ip, string clazz, string method, string result) {this. userid = userID; this. username = userName; this. ip = ip; this. clazz = clazz; this. method = method; this. result = result;} private string userid; public string Userid {get {return userid;} set {userid = value;} private string username; public string Username {get {return username;} set {username = value ;}} private string ip; public string Ip {get {return ip ;}set {ip = value ;}} private string clazz; public string Clazz {get {return clazz;} set {clazz = value ;}} private string method; public string Method {get {return method ;} set {method = value ;}} private string result; public string Result {get {return result ;}set {result = value ;}}}}


The second CustomLayout class.

This class customizes the log output type. The implementation idea is to put the Custom field into Hashtable, and Add as many custom fields as possible. The field name is consistent with the configuration file, the namespace corresponds to the following part of the configuration file.


Using System; using System. collections; using System. IO; using log4net. core; using log4net. layout. pattern; using log4net. util; using log4net. layout; namespace LogDB {public class CustomLayout: log4net. layout. layoutSkeleton {public const string DefaultConversionPattern = "% message % newline"; public const string DetailConversionPattern = "% timestamp [% thread] % level % logger % ndc-% message % newline"; privat E static Hashtable s_globalRulesRegistry; private string m_pattern; private PatternConverter m_head; private Hashtable vertex = new Hashtable (); static CustomLayout () {s_globalRulesRegistry = new Hashtable (6 ); struct ("username", typeof (UserNamePatternConverter); s_globalRulesRegistry.Add ("userid", typeof (UserIdPatternConverter); s_globalRulesRegistry.Add ("ip", Typeof (IpPatternConverter); iterator ("clazz", typeof (ClazzPatternConverter); iterator ("method", typeof (MethodPatternConverter); s_globalRulesRegistry.Add ("result ", typeof (ResultPatternConverter);} // initialize public CustomLayout (): this (DefaultConversionPattern) {} public CustomLayout (string patte Rn) {IgnoresException = true; m_pattern = pattern; if (m_pattern = null) {m_pattern = defaconverconversionpattern;} ActivateOptions ();} public string ConversionPattern {get {return m_pattern ;} set {m_pattern = value ;}} /// <summary> /// convert the value in Hashtable /// </summary> /// <param name = "pattern"> </param> /// <returns> </returns> virtual protected PatternParser CreatePatternParser (string patt Ern) {PatternParser patternParser = new PatternParser (pattern); foreach (DictionaryEntry entry in s_globalRulesRegistry) {patternParser. patternConverters [entry. key] = entry. value;} foreach (DictionaryEntry entry in m_instanceRulesRegistry) {patternParser. patternConverters [entry. key] = entry. value;} return patternParser;} override public void ActivateOptions () {m_head = CreatePatternParser (m _ Pattern). Parse (); PatternConverter curConverter = m_head; while (curConverter! = Null) {PatternLayoutConverter layoutConverter = curConverter as PatternLayoutConverter; if (layoutConverter! = Null) {if (! LayoutConverter. ignoresException) {this. ignoresException = false; break;} curConverter = curConverter. next ;}} override public void Format (TextWriter writer, LoggingEvent loggingEvent) {if (writer = null) {throw new ArgumentNullException ("writer ");} if (loggingEvent = null) {throw new ArgumentNullException ("loggingEvent");} PatternConverter c = m_head; while (c! = Null) {c. format (writer, loggingEvent); c = c. next ;}} public void AddConverter (ConverterInfo converterInfo) {AddConverter (converterInfo. name, converterInfo. type);} public void AddConverter (string name, Type type) {if (name = null) throw new ArgumentNullException ("name"); if (type = null) throw new ArgumentNullException ("type"); if (! Typeof (PatternConverter ). isAssignableFrom (type) {throw new ArgumentException ("The converter type specified [" + type + "] must be a subclass of log4net. util. patternConverter "," type ");} m_instanceRulesRegistry [name] = type;} public sealed class ConverterInfo {private string m_name; private Type m_type; public ConverterInfo () {} public string Name {get {return m_name;} set {m_name = value ;}} public Type {get {return m_type ;} set {m_type = value ;}}}}}


Then there are a series of classes such as UserIdPatternConverter/UserNamePatternConverter/IpPatternConverter. The number of custom fields is the same as that under customLayout.


LogUtil class.

The logUtil class encapsulates the logging method, which is called externally. The parameters are defined fields and the log4net method is called in the method body.


Using log4net; // <summary> // LogUtil abstract description /// </summary> public class LogUtil {public LogUtil () {} private LogDB. logMessage message = null; public void WriteLog (string strLoggerName, string userID, string userName, string ip, string clazz, string method, string result) {log4net. ILog log = log4net. logManager. getLogger (strLoggerName); message = new LogDB. logMessage (userID, userName, ip, clazz, method, result); // use the field auxiliary class log. info (message );}}


Test our project.

Add default. aspx and write the test in the background code:


namespace LogDB{    public partial class Default : System.Web.UI.Page    {        protected void Page_Load(object sender, EventArgs e)        {            LogUtil logUtil = new LogUtil();            logUtil.WriteLog("AuthoritySystem", "1", "1", "1", "1", "1", "1");            logUtil.WriteLog("BaseSystem", "1", "1", "1", "1", "1", "1");            logUtil.WriteLog("ExamSystem", "1", "1", "1", "1", "1", "1");            logUtil.WriteLog("EvaluationSystem", "1", "1", "1", "1", "1", "1");            logUtil.WriteLog("FreshSystem", "1", "1", "1", "1", "1", "1");        }    }}


After generation, all operations are recorded in the database, and the logs of the five subsystems are recorded in five tables respectively.


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.