Log4net modifies database connection strings and writes custom information. log4net database connection

Source: Internet
Author: User

Log4net modifies database connection strings and writes custom information. log4net database connection

Recently, log4net needs to be used to write logs. Because the entire platform is on sharepoint, we need to record the logs generated by specific sub-sites, therefore, you need to add a custom information column in the original log table. Due to the platform's security requirements, we need to encrypt the connection string. The information of the connection string is read in AdoNetAppender, so we need to extend this class. For custom messages, we need to extend the PatternLayout class. In fact, there have been a lot of Introduction to log4net on the Internet, such as the use of log4net. dll

The specific code is as follows:

  #region Log helper    public class LogMessage    {        public string CustomMessage { get; set; }        public string Message { get; set; }        public override string ToString()        {            return Message;        }    }    internal class CustomMessageConverter : PatternLayoutConverter    {        protected override void Convert(TextWriter writer, log4net.Core.LoggingEvent loggingEvent)        {            var logMessage = loggingEvent.MessageObject as LogMessage;            if (logMessage != null)            {                writer.Write(logMessage.CustomMessage);            }        }    }    internal class CustomLayout : PatternLayout    {        public CustomLayout()        {            this.AddConverter("CustomMessage", typeof(CustomMessageConverter));        }    }    public class CustAdoNetAppender : AdoNetAppender    {        string _connectiongStr = string.Empty;        public new string ConnectionString        {            set            {                _connectiongStr = value;                base.ConnectionString = _connectiongStr;            }            get            {                return base.ConnectionString;            }        }    }    #endregion

Configuration code

<? Xml version = "1.0" encoding = "UTF-8"?> <Configuration> <configSections> <section name = "log4net" type = "log4net. config. log4NetConfigurationSectionHandler, log4net "/> </configSections> <log4net> <logger name =" MyLogger "> <level value =" ALL "> </level> <appender-ref =" ADONetAppender"> </appender-ref> </logger> <! -- Record logs to the database --> <appender name = "ADONetAppender" type = "leleapp. custAdoNetAppender "> <bufferSize value =" 100 "/> <connectionType value =" System. data. sqlClient. sqlConnection, System. data, Version = 1.0.3300.0, Culture = neutral, PublicKeyToken = b77a5c561934e089 "/> <connectionString value =" data source = .; initial catalog = test; integrated security = false; persist security info = True; User ID = sa; Password = xxx "/> <commandText value =" insert into Log ([Date], [Thread], [Level], [Logger], [Message], [CustomMessage]) VALUES (@ log_date, @ thread, @ log_level, @ logger, @ message, @ customMessage) "/> <parameter> <parameterName value =" @ log_date "/> <dbType value =" DateTime "/> <layout type =" log4net. layout. rawTimeStampLayout "/> </parameter> <parameterName value =" @ thread "/> <dbType value =" String "/> <size value =" 255 "/> <layout type = "log4net. layout. patternLayout "> <conversionPattern value =" % thread "/> </layout> </parameter> <parameterName value =" @ log_level "/> <dbType value =" String "/> <size value =" 50 "/> <layout type =" log4net. layout. patternLayout "> <conversionPattern value =" % level "/> </layout> </parameter> <parameterName value =" @ logger "/> <dbType value =" String & quot;/> <size value = "255"/> <layout type = "log4net. layout. patternLayout "> <conversionPattern value =" % logger "/> </layout> </parameter> <parameterName value =" @ message "/> <dbType value =" String & quot;/> <size value = "4000"/> <layout type = "log4net. layout. patternLayout "> <conversionPattern value =" % message "/> </layout> </parameter> <parameterName value =" @ customMessage "/> <dbType value =" String "/> <size value =" 4000 "/> <layout type =" leleapp. customLayout "> <conversionPattern value =" % CustomMessage "/> </layout> </parameter> </appender> </log4net> </configuration>

 

The SQL script is as follows:

     CREATE TABLE [dbo].[Log] (        [ID] [int] IDENTITY (1, 1) NOT NULL ,       [Date] [datetime] NOT NULL ,       [Thread] [varchar] (255) NOT NULL ,       [Level] [varchar] (20) NOT NULL ,       [Logger] [varchar] (255) NOT NULL ,       [Message] [varchar] (4000) NOT NULL ,       [CustomMessage] VARCHAR(max) NULL     ) ON [PRIMARY]

Add a sentence to the AssemblyInfo. cs File

[Assembly: log4net. Config. DOMConfigurator (ConfigFile = "Log4Net. xml", Watch = true)]

Call code:

ILog log = LogManager. GetLogger ("MyLogger ");
Log. Info (new LogMessage {Message = "message", CustomMessage = "cust "});

Running result:


How can I change the connection string to the password of the local database after attaching the database to net? For beginners, you can describe them in detail,

Didn't you find the connection string? Search for the text file with the config extension.
This is generally the case.
Data Source =.; Initail Catalog = database; UID = username; PWD = password;

How should I configure the database connection string in the webconfig file of aspnet?

The reason for using web. config is that some settings often need to be changed. It is best for web. config to define parameters without changing the program code.
<ConnectionStrings>
<Add name = "project name" connectionString = "Data Source = IP address you want to set (if it is SQL2005 or above or if one machine is installed with multiple versions of SQL, you need to add SQL after the IP address instance name ); user ID = User name; Password = Password; persist security info = False; initial catalog = database name; "providerName =" System. data. sqlClient "/>
</ConnectionStrings>

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.