Use an independent configuration file for Log4net multi-assembly

Source: Internet
Author: User
Document directory
  •  
Multiple assemblies use independent configuration files in the same process.

In normal software development, some third-party libraries are often used. Third-party libraries and our programs use log4net for logging, by default, we use the same configuration to use the log4net configuration file. However, in many cases, the log configuration we need and the log configuration information of third-party class libraries need to be independent. In this case, how can this problem be solved?

The solution structure is as follows:

The application SimpleApp and SharedModule use the same configuration, and the third-party class library SimpleModule uses independent configuration.

Source code of SimpleApp EntryPoint

#RegionCopyright & License

//

// Copyright 2001-2005 The Apache Software Foundation

//

// Licensed under the Apache License, Version 2.0 (the "License ");

// You may not use this file except T in compliance with the License.

// You may obtain a copy of the License

//

// Http://www.apache.org/licenses/LICENSE-2.0

//

// Unless required by applicable law or agreed to in writing, software

// Distributed under the License is distributed on an "as is" BASIS,

// Without warranties or conditions of any kind, either express or implied.

// See the License for the specific language governing permissions and

// Limitations under the License.

//

#Endregion

// Configure logging for this assembly using the 'SimpleApp.exe. log4net' file

// Configure the log4net monitoring configuration file with the suffix log4net

[Assembly: log4net. Config. XmlConfigurator (ConfigFileExtension = "log4net", Watch = true)]

// The following alias attribute can be used to capture the logging

// Repository for the 'simplemodule' assembly. Without specifying this

// Attribute the logging configuration for the 'simplemodule' assembly

// Will be read from the 'simplemodule. dll. log4net' file. When this

// Attribute is specified the configuration will be shared with this

// Assemby's configuration.

// [Assembly: log4net. Config. AliasRepository ("SimpleModule")]

NamespaceSimpleApp

{

UsingSystem;

/// <Summary>

/// Summary description for Class1.

/// </Summary>

PublicClass EntryPoint

{

// Create a logger for use in this class

PrivateStatic readonly log4net. ILog log = log4net. LogManager.GetLogger(System. Reflection. MethodBase.GetCurrentMethod(). DeclaringType );

/// <Summary>

/// The main entry point for the application.

/// </Summary>

[STAThread]

PublicStatic voidMain(String [] args)

{

Args =NewString [] {"3", "7 "};

If(Log. IsInfoEnabled) log.Info(Args );

If(Args. Length! = 2)

{

Log.Error("Must supply 2 command line arguments ");

}

Else

{

IntLeft =Int.Parse(Args [0]);

IntRight =Int.Parse(Args [1]);

IntResult = 0;

If(Log. IsDebugEnabled) log.Debug("Adding [" + left + "] to [" + right + "]");

Result = (NewSimpleModule.Math()).Add(Left, right );

If(Log. IsDebugEnabled) log.Debug("Result [" + result + "]");

Console. Out.WriteLine(Result );

If(Log. IsDebugEnabled) log.Debug("Subtracting [" + right + "] from [" + left + "]");

Result = (NewSharedModule.Math()).Subtract(Left, right );

If(Log. IsDebugEnabled) log.Debug("Result [" + result + "]");

Console. Out.WriteLine(Result );

}

Console.Read();

}

}

}

SimpleApp.exe. log4net Configuration

<? Xml version = "1.0" encoding = "UTF-8"?>

<! -- This section contains the log4net configuration settings -->

<Log4net>

<! -- Define some output appenders -->

<Appender name = "leleappender" type = "log4net. Appender. ConsoleAppender">

<Layout type = "log4net. Layout. PatternLayout">

<ConversionPattern value = "[SimpleAppConfig] % date [% thread] %-5 level % logger-% message % newline"/>

</Layout>

</Appender>

<Appender name = "LogFileAppender" type = "log4net. Appender. FileAppender">

<File value = "log-file.txt"/>

<! -- Example using environment variables in params -->

<! -- <File value = "$ {TMP} \ log-file.txt"/> -->

<AppendToFile value = "true"/>

<! -- An alternate output encoding can be specified -->

<! -- <Encoding value = "unicodeFFFE"/> -->

<Layout type = "log4net. Layout. PatternLayout">

<Header value = "[Header]
"/>

<Footer value = "[Footer]
"/>

<ConversionPattern value = "% date [% thread] %-5 level % logger [% ndc] & lt; % property {auth} & gt;-% message % newline"/>

</Layout>

<! -- Alternate layout using XML

<Layout type = "log4net. Layout. XMLLayout"/> -->

</Appender>

<! -- Setup the root category, add the appenders and set the default level -->

<Root>

<Level value = "DEBUG"/>

<Appender-ref = "leleappender"/>

<Appender-ref = "LogFileAppender"/>

</Root>

</Log4net>

SimpleModule project Math. cs code

#RegionCopyright & License

//

// Copyright 2001-2005 The Apache Software Foundation

//

// Licensed under the Apache License, Version 2.0 (the "License ");

// You may not use this file except T in compliance with the License.

// You may obtain a copy of the License

//

// Http://www.apache.org/licenses/LICENSE-2.0

//

// Unless required by applicable law or agreed to in writing, software

// Distributed under the License is distributed on an "as is" BASIS,

// Without warranties or conditions of any kind, either express or implied.

// See the License for the specific language governing permissions and

// Limitations under the License.

//

#Endregion

// We want this assembly to have a seperate logging repository to

// Rest of the application. We will configure this repository seperatly.

// Set the configuration file to use independent Configuration

[Assembly: log4net. Config. Repository ("SimpleModule")]

// Configure logging for this assembly using the 'simplemodule. dll. log4net' file

// Configure the log4net monitoring configuration file with the suffix log4net

[Assembly: log4net. Config. XmlConfigurator (ConfigFileExtension = "log4net", Watch = true)]

NamespaceSimpleModule

{

/// <Summary>

/// Summary description for Math.

/// </Summary>

PublicClass Math

{

// Create a logger for use in this class

PrivateStatic readonly log4net. ILog log = log4net. LogManager.GetLogger(System. Reflection. MethodBase.GetCurrentMethod(). DeclaringType );

PublicMath()

{

If(Log. IsDebugEnabled) log.Debug("Constructor ");

}

PublicIntAdd(IntLeft,IntRight)

{

IntResult = left + right;

If(Log. IsInfoEnabled) log.Info("" + Left + "+" + right + "=" + result );

Return result;

}

}

}

SimpleModule. dll. log4net Configuration

<? Xml version = "1.0" encoding = "UTF-8"?>

<! -- This section contains the log4net configuration settings -->

<Log4net>

<! -- Define some output appenders -->

<Appender name = "leleappender" type = "log4net. Appender. ConsoleAppender">

<! -- <File value = "SimpleModule.txt"/> -->

<Layout type = "log4net. Layout. PatternLayout">

<ConversionPattern value = "[hbb0b0SimpleModuleConfig] % date [% thread] %-5 level % logger-% message % newline"/>

</Layout>

</Appender>

<! -- Setup the root category, add the appenders and set the default priority -->

<Root>

<Level value = "DEBUG"/>

<Appender-ref = "leleappender"/>

</Root>

</Log4net>

Program output

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.