背景:
阅读新闻

Create a log4net logger in code

  作者: 今日评论: [字体: ]

I found myself requiring to instantiate a log4net logger in code (not through the xml configuration).
However, there are a few things that I haven’t worked around yet, here’s the code I came up with.


var hierarchy = (Hierarchy)LogManager.GetRepository();
var logger = hierarchy.LoggerFactory.CreateLogger((ILoggerRepository)hierarchy, "logname");
logger.Hierarchy = hierarchy;
 
logger.AddAppender(CreateFileAppender());
logger.AddAppender(CreateDbAppender());
 
logger.Repository.Configured = true;
 
// alternative use the LevelMap to set the Log level based on a string
// hierarchy.LevelMap["ERROR"]
hierarchy.Threshold = Level.Debug;
logger.Level = Level.Debug;
 
ILog log = new LogImpl(logger);
 
log.Error(“This is my error message”);



Note that setting the level needs to be both on the hierarchy and the logger. This is based on the log4net hierarchy implementation.

Creating the Appenders is quite simple.




private IAppender CreateFileAppender()
{
    var fileAppender = new RollingFileAppender
    {
        Name = "myFileAppenderName",
        File = "logfile.log",
        LockingModel = new FileAppender.MinimalLock(),
        AppendToFile = true,
        RollingStyle = RollingFileAppender.RollingMode.Size,
        MaxSizeRollBackups = 2,
        MaximumFileSize = "1MB",
        StaticLogFileName = true,
        Layout = new log4net.Layout.PatternLayout("%d [%t] %-5p %c %m%n")
    };
    fileAppender.ActivateOptions();
    return fileAppender;
}
 
private IAppender CreateDBAppender()
{
    RawLayoutConverter layoutConverter = new RawLayoutConverter();
 
    var databaseAppender = new AdoNetAppender
    {
        Name = "myDbAppender",
        ConnectionString = connectionStringBuilder.ConnectionString,
        CommandText = @"INSERT INTO [Log] ([DateTime], [Exception], [Level], [Logger], [Message], [Thread])
                        VALUES (@logdate, @exception, @level, @logger, @message, @thread)",
        CommandType = System.Data.CommandType.Text,
        ConnectionType = "System.Data.SqlClient.SqlConnection",
        UseTransactions = true
    };
 
    databaseAppender.AddParameter(new AdoNetAppenderParameter
        {
            ParameterName = "@logdate",
            DbType = System.Data.DbType.DateTime,
            Layout = new RawTimeStampLayout()
        });
 
    databaseAppender.AddParameter(new AdoNetAppenderParameter
        {
            ParameterName = "@message",
            DbType = System.Data.DbType.String,
            Size = 4000,
            Layout = (IRawLayout)layoutConverter.ConvertFrom(new PatternLayout("%m"))
        });
 
    databaseAppender.AddParameter(new AdoNetAppenderParameter
        {
            ParameterName = "@exception",
            DbType = System.Data.DbType.String,
            Size = 2000,
            Layout = (IRawLayout)layoutConverter.ConvertFrom(new ExceptionLayout())
        });
 
    databaseAppender.AddParameter(new AdoNetAppenderParameter
        {
            ParameterName = "@level",
            DbType = System.Data.DbType.String,
            Size = 50,
            Layout = (IRawLayout)layoutConverter.ConvertFrom(new PatternLayout("%-5p"))
        });
 
    databaseAppender.AddParameter(new AdoNetAppenderParameter
        {
            ParameterName = "@logger",
            DbType = System.Data.DbType.String,
            Size = 255,
            Layout = (IRawLayout)layoutConverter.ConvertFrom(new PatternLayout("%c"))
        });
 
    databaseAppender.AddParameter(new AdoNetAppenderParameter
        {
            ParameterName = "@thread",
            DbType = System.Data.DbType.String,
            Size = 255,
            Layout = (IRawLayout)layoutConverter.ConvertFrom(new PatternLayout("%t"))
        });
 
    databaseAppender.ActivateOptions();
    return databaseAppender;
}


The one thing I could not get to work is accessing the logger through the default way for accessing a logger.

LogManager.GetLogger("logname");


This action will create a new logger, with the same name, but will not use my registered version. This means the logger has no appenders registered.

If anyone knows how this can be accomplished, please let me know.

My actual goals was to accomplish following xml configuration through code where I would only configure some appenders to a specific logger without needing to add them to the root.

<root>
    <level value="DEBUG" />
</root>
<logger name="mylogger">
    <level value="ERROR" />
    <appender-ref ref="myFileAppender" />
    <appender-ref ref="myDbAppender" />
</logger>


来源:http://www.ronaldrosier.net/Blog/2013/05/11/create_a_log4net_logger_in_code
录入日期:[2016/07/01 14:05:00]
收藏 推荐 打印 | 录入:mikebai | 阅读:
文章评论      
正在加载评论列表...
评论表单加载中...