问题描述
|
这是我的情况:我有一个图书馆项目,旨在覆盖log4net并使用自定义附加程序集中日志。我有这些课:
myCustomLogManager
CustomLog
ICustomLog
在myCustomLogManager中,我得到了:
public class myCustomLogManager
{
public static ICustomLog GetLogger(System.Type t)
{
return new CustomLog(t);
}
// Other stuff
}
我的自定义日志:
class CustomLog : ICustomLog
{
private static ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public CustomLog(System.Type t)
{
log = LogManager.GetLogger(t);
}
public void Debug( string message,Exception e)
{
log.Debug(message,e);
}
}
在每个类中,我在控制台应用程序项目中声明:
private static readonly ICustomLog logger = myCustomLogManager.GetLogger(typeof(myClass));
当我登录myClass时,没问题。但是,如果我也使用另一个要登录的类(例如myOtherClass),则我以后在myClass中登录的记录器名称将具有值“ myOtherClass \”。为了说明问题,这是输出示例:
[Info] myProject.myClass:\“来自myClass的日志!\”
[Info] myProject.myOtherClass:\“来自myOtherClass的日志!\”
[Info] myProject.myOtherClass:\“来自myClass的第二条日志!\”
这很难解释,我希望我已经足够清楚了,但事实是默认记录器,在myOtherClass类中完成操作后为myProject.myOtherClass,当我登录myClass时不会回到myProject.myClass类。
我怎样才能解决这个问题?
感谢您的阅读和帮助:-)
解决方法
使ѭ5中的ѭ4变为非静态:
private ILog log;
(也无需将其初始化为任何东西)
通过具有一个静态字段,您实际上只有一个记录器,因此,当您使用日志管理器为第二类获得一个“新”记录器时,它会被更改。