我正在创建两个附加程序,如下所示:
private RollingFileAppender GetNewFileApender()
{
log4net.Appender.RollingFileAppender appender = new log4net.Appender.RollingFileAppender();
appender.Name = _serviceName;
appender.File = _configFileName;
appender.AppendToFile = true;
appender.MaxSizeRollBackups = 10;
appender.MaximumFileSize = "10MB";
appender.StaticLogFileName = true;
appender.RollingStyle = RollingFileAppender.RollingMode.Size;
appender.DatePattern = "yyyy.MM.dd";
appender.Layout = new log4net.Layout.PatternLayout("%d %p %m%n");
appender.ActivateOptions();
return appender;
}
它们在文件名日志文件方面都不同。现在我想为特定的 appender 获取 ILog。
一般来说,我希望有两个 ILog 类型的变量,这样我就可以在应用程序的任何地方写入特定的日志文件。
更新
这是我面临的问题的完整代码:
using System;
using System.Collections;
using log4net;
using log4net.Appender;
using log4net.Repository.Hierarchy;
namespace Log4netTest
{
public class Logger4net
{
private static ArrayList ServicesNames = new ArrayList();
private ILog _logger;
private string _serviceName;
private string _configFileName;
private Logger4net(string ServiceName)
{
if (ServicesNames.Contains(ServiceName))
throw new Exception(string.Format("Service {0} exists", ServiceName));
ServiceName = ServiceName.Trim();
_serviceName = ServiceName;
_configFileName = string.Format("{0}.log", _serviceName);
}
private RollingFileAppender GetNewFileApender()
{
log4net.Appender.RollingFileAppender appender = new log4net.Appender.RollingFileAppender();
appender.Name = _serviceName;
appender.File = _configFileName;
appender.AppendToFile = true;
appender.MaxSizeRollBackups = 10;
appender.MaximumFileSize = "10MB";
appender.StaticLogFileName = true;
appender.RollingStyle = RollingFileAppender.RollingMode.Size;
appender.DatePattern = "yyyy.MM.dd";
var layout = new log4net.Layout.PatternLayout("%d %p %m%n");
appender.Layout = layout;
layout.ActivateOptions();
appender.ActivateOptions();
return appender;
}
public static Logger4net AddNewLogger4net(string ServiceName)
{
Logger4net result = new Logger4net(ServiceName);
var newappender = result.GetNewFileApender();
log4net.Config.BasicConfigurator.Configure(newappender);
result._logger = log4net.LogManager.GetLogger(ServiceName);
Logger l = (Logger)result._logger.Logger;
l.AddAppender(newappender);
return result;
}
public void AddInfo(string message)
{
_logger.Info(string.Format("{0}: {1}", _serviceName, message));
}
}
class Program
{
static void Main(string[] args)
{
Logger4net log1 = Logger4net.AddNewLogger4net("Service1");
Logger4net log2 = Logger4net.AddNewLogger4net("Service2");
log1.AddInfo("Test 1");
log2.AddInfo("Test 2");
/*
in Service1.log I have:
2012-09-25 14:49:30,666 INFO Service1: Test 1
2012-09-25 14:49:30,666 INFO Service1: Test 1
2012-09-25 14:49:30,666 INFO Service2: Test 2
in Service2.log I have:
2012-09-25 14:49:30,666 INFO Service1: Test 1
2012-09-25 14:49:30,666 INFO Service2: Test 2
2012-09-25 14:49:30,666 INFO Service2: Test 2
*
* i would like to have Test 1 in Service1.log and Test 2 in Service2.log
*/
}
}
}