我有一个 log4net 包装类...但是每次从其他类调用它以记录错误时,我都需要实例化。我需要克服这个问题。最近我遇到了我不熟悉的单例类。因此我需要帮助将我当前的包装类转换为单例类。
我在下面发布我目前正在使用的 log4net 包装器类..
using System;
using System.Data;
using System.Configuration;
using Asset.Business;
/// <summary>
/// Summary description for Logger
/// </summary>
namespace AssetsDataService
{
public class ErrorLogger
{
private static log4net.ILog logger = null;
public ErrorLogger()
{
if (logger == null)
{
string logConfigPath = ConfigSettings.GetEnvConfigValue("LogConfigXMLPath"); // this contains the path of the xml
System.IO.FileInfo fileInfo = new System.IO.FileInfo(logConfigPath);
log4net.Config.DOMConfigurator.Configure(fileInfo);
string loggerName = ConfigurationManager.AppSettings.Get("ErrorLoggerName"); // this contains the name of the logger class
logger = log4net.LogManager.GetLogger(loggerName);
}
}
public void Fatal(Object message)
{
logger.Fatal(message);
}
public void Fatal(Object message, Exception exception)
{
logger.Fatal(message, exception);
}
public void Error(Object message)
{
logger.Error(message);
}
public void Error(Object message, Exception exception)
{
logger.Error(message, exception);
}
public void Debug(Object message)
{
logger.Debug(message);
}
public void Info(Object message)
{
logger.Info(message);
}
}
}
这是我试图使我的包装类单例的代码:
using System;
using System.Data;
using System.Configuration;
using Asset.Business;
/// <summary>
/// Summary description for Logger
/// </summary>
namespace AssetsDataService
{
public class ErrorLogger
{
private static volatile ErrorLogger instance;
private static object syncRoot = new Object();
private static log4net.ILog logger = null;
private ErrorLogger()
{
if (logger == null)
{
string logConfigPath = ConfigSettings.GetEnvConfigValue("LogConfigXMLPath"); // this contains the path of the xml
System.IO.FileInfo fileInfo = new System.IO.FileInfo(logConfigPath);
log4net.Config.DOMConfigurator.Configure(fileInfo);
string loggerName = ConfigurationManager.AppSettings.Get("ErrorLoggerName"); // this contains the name of the logger class
logger = log4net.LogManager.GetLogger(loggerName);
}
}
public static ErrorLogger Instance()
{
if (instance == null)
{
lock (syncRoot)
{
if (instance == null)
instance = new ErrorLogger();
}
}
return instance;
}
public void Fatal(Object message)
{
logger.Fatal(message);
}
public void Fatal(Object message, Exception exception)
{
logger.Fatal(message, exception);
}
public void Error(Object message)
{
logger.Error(message);
}
public void Error(Object message, Exception exception)
{
logger.Error(message, exception);
}
public void Debug(Object message)
{
logger.Debug(message);
}
public void Info(Object message)
{
logger.Info(message);
}
}
}
这个类是一个正确的单例类,它会正确处理日志吗?
我将如何调用记录器 ErrorLogger 类来记录错误或信息等。
通过使用我的普通课程,我曾经将其称为
ErrorLogger log = new ErrorLogger();
log.Error(string.Concat("Exception Occurred :" + ex.Message, "/n", ex.StackTrace));
如果我使用单例类,我如何登录?