(2) Use log4net to write custom database logs and log4net Databases

Source: Internet
Author: User
Tags log4net

(2) Use log4net to write custom database logs and log4net Databases
1. Configure the Project Environment

1.1 this article only shows the operations to modify the configuration. For the first time you introduce the log4net environment, refer to the above.

1.2 install the mysql-connector-net.msi environment ,. And manually generate the database log information table.

2. Configure log4net. config

2.1 modify log4net. config

<? Xml version = "1.0" encoding = "UTF-8"?> <Configuration> <log4net> <! -- Mysql Log class --> <logger name = "logdb"> <level value = "ALL"/> <appender-ref = "AdoNetAppender_Mysql"/> </logger> <! -- Mysql Log additional media --> <appender name = "AdoNetAppender_Mysql" type = "log4net. Appender. AdoNetAppender"> <! -- The buffer size of the log information. The value is 0 during testing. You can change the size of the buffer to 100 for actual deployment. --> <bufferSize value = "0"/> <! -- Mysql-connector-net is later than 6.8.3, and the data source does not need to be changed --> <ConnectionType value = "MySql. data. mySqlClient. mySqlConnection, MySql. data, Version = 6.8.3.0, Culture = neutral, PublicKeyToken = c5687fc88969c44d "/> <! -- Database connection string --> <ConnectionString value = "server = localhost; user id = root; password = root; persist security info = True; character set = utf8; database = test; pooling = true; "/> <! -- Database Log insertion command --> <commandText value = "insert into loginfo (DateTime, Message, UserId) VALUES (@ log_date, @ message, @ user_id) "/> <parameter> <parameterName value =" @ log_date "/> <dbType value =" DateTime "/> <layout type =" log4net. layout. rawTimeStampLayout "/> </parameter> <parameterName value =" @ message "/> <dbType value =" String "/> <size value =" 255 "/> <layout type = "log4net. layout. patternLayo Ut "> <conversionPattern value =" % message "/> </layout> </parameter> <! -- The format includes property as custom information --> <parameter> <parameterName value = "@ user_id"/> <dbType value = "String"/> <size value = "255 "/> <layout type = "log4net. layout. patternLayout "> <conversionPattern value =" % property {UserId} "/> </layout> </parameter> </appender> </log4net> </configuration>
3. Sample Code

3.1 modify LogHelper

Namespace July. demo. win {public class LogHelper {static readonly log4net. ILog logdb = log4net. logManager. getLogger ("logdb"); public static void WriteLog (string info) {if (logdb. isInfoEnabled) {// Use thread-related attributes to set custom information log4net. threadContext. properties ["UserId"] = "U-1001"; logdb. info (info );}}}}
4. Running Effect

4.1 as follows


Log4net in c # development instance, and output logs to SQL database

Zhou Gong's blog-log4net Usage Details:
Blog.csdn.net/..3.aspx
Very detailed.

How to Use Log4net to create logs

First, let's analyze the working principle of Log4net: Log4net is a very famous open-source component for recording logs developed based on. NET. It uses a set of log engines configured in XML to classify logs into different levels: FATAL, ERROR, WARN, INFO, DEBUG, and ALL (allow ALL log requests) and OFF (reject all log requests). The default value is DEBUG. The first five items are similar to the errors we encounter when debugging applications, in the compiler, prompts such as errors and warnings are also left, and their error levels are constantly decreasing. Let's look at the core components of Log4net. Log4net consists of five parts: Logger, Appenders, Filters, Layouts, and Object Renders. 1) Logger: mainly responsible for logging. It can be recorded in multiple ways, such as files, databases, consoles, and emails. 2) Appenders: it is mainly responsible for recording the log media. Its output methods mainly include AdoNetAppender, which records logs to the database. You can use SQL or stored procedures. AspNetTraceAppender: You can trace logs in ASP. NET. BufferingForwardingAppender: cache log events before outputting them to sub-Appenders. ColoredConsoleAppender: Write high-brightness log events in the terminal window. ConsoleAppender: outputs logs to the console. EventLogAppender: writes logs to Windows operating system logs. FileAppender: Write logs to files. ForwardingAppender: used to specify a group of constraints for an Appender. MemoryAppender: stores logs in the memory buffer. NetSendAppender: outputs logs to the Windows Messenger service. The logs are displayed in the user terminal dialog box. OutputDebugStringAppender: configure this Appender to write logs to the OutputDebugString API. RemotingAppender: writes logs to the remote acceptor through. NET Remoting. RollingFileAppender: writes logs to a file in the form of a rollback file. SmtpAppender: Write logs to emails. SmtpPickupDirAppender: the configuration is similar to that of SmtpAppender, but replace SmtpHost with PickupDir. TraceAppender: Write logs to the. NET trace system. UdpAppender: Send Logs in the form of connectionless UDP multicast Rams to a remote host or broadcast logs in the form of UdpClient. Some of the above output methods may be used frequently, and some may not be used frequently. The specific examples are as follows. 3) Layouts: it is mainly responsible for formatting and outputting record logs. The display formats are as follows: % timestamp [% thread] %-5 level % logger {2} % ndc-% message % newline timestamp: indicates the time when the program has started running. Unit: [millisecond]. Thread: the Thread that executes the current code. Level: the log Level. Logger: the name of the log-related request.

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.