欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

代码设定Log4net

程序员文章站 2022-06-25 16:04:59
在下面这个示例中,我将创建一个向控制台和"a.log"文件中写入日志的log [csharp] using system;  using sys...

在下面这个示例中,我将创建一个向控制台和"a.log"文件中写入日志的log

[csharp]
using system; 
using system.collections.generic; 
using system.linq; 
using system.text; 
using log4net; 
using log4net.appender; 
using log4net.layout; 
using log4net.repository.hierarchy; 
 
namespace mylog4net 

    public class mylog4net 
    { 
        public static ilog getmylog(dynamic logname) 
        { 
            ilog log = null; 
            if (logname is string) 
            { 
                string name = (string)logname; 
                log = log4net.logmanager.getlogger(name); 
            } 
            else if (logname is type) 
            { 
                type t = (type)logname; 
                log = log4net.logmanager.getlogger(t); 
            } 
            else 
            { 
                throw new exception("parameter must be a string or type value!"); 
            } 
            fileappender fa = new fileappender(); 
            fa.name = "fileappender1"; 
            fa.file = "a.log"; 
            fa.appendtofile = true; 
            consoleappender ca = new consoleappender(); 
            ca.name = "consoleappender1"; 
            patternlayout pl = new patternlayout(); 
            pl.conversionpattern = "[%d] - %p : %c => %m%n"; 
            pl.activateoptions(); 
            fa.layout = pl; 
            fa.activateoptions(); 
            ca.layout = pl; 
            ca.activateoptions(); 
            hierarchy h = (hierarchy)logmanager.getrepository(); 
            h.root.level = h.levelmap["debug"]; 
            h.root.addappender(fa); 
            h.root.addappender(ca); 
            h.configured = true; 
            return log; 
        } 
    } 

 


摘自 tx_officedev的专栏