.NET 日志记录类无法写入
我刚刚根据我在 MSDN 和其他一些网站上找到的示例编写了一个简单的日志记录类,供在各种线程之间使用。问题是,它创建文件日志文件,但实际上从未向其中写入任何内容(尽管它会正确写入控制台)。
public class Logger
{
private static Logger instance;
private Logger() { }
private static StreamWriter writer;
public static Logger GetInstance()
{
lock (typeof(Logger))
{
if (instance == null)
{
instance = new Logger();
}
return instance;
}
}
public void OpenFile(String file)
{
// Open log file for writing and append to it
writer = new StreamWriter(file, true);
}
public void LogMessage(String message)
{
string dt = DateTime.Now.ToString("yyyy-MM-dd H:mm:ss :: ");
writer.WriteLine(dt + message);
Console.WriteLine(dt + message);
}
public void LogError(String error)
{
string dt = DateTime.Now.ToString("yyyy-MM-dd H:mm:ss :: ");
writer.WriteLine(dt + "ERROR: " + error);
Console.WriteLine(dt + "ERROR: " + error);
}
}
我正在我的程序中执行以下操作。
static void Main(string[] args)
{
Logger log = Logger.GetInstance();
log.OpenFile("app.log");
log.LogMessage("Starting App...");
I just wrote a simple logging class for use among various threads, based on examples I found at MSDN and a few other sites. Problem is, it creates the file log file, but never actually writes anything to it (it writes to the console properly though).
public class Logger
{
private static Logger instance;
private Logger() { }
private static StreamWriter writer;
public static Logger GetInstance()
{
lock (typeof(Logger))
{
if (instance == null)
{
instance = new Logger();
}
return instance;
}
}
public void OpenFile(String file)
{
// Open log file for writing and append to it
writer = new StreamWriter(file, true);
}
public void LogMessage(String message)
{
string dt = DateTime.Now.ToString("yyyy-MM-dd H:mm:ss :: ");
writer.WriteLine(dt + message);
Console.WriteLine(dt + message);
}
public void LogError(String error)
{
string dt = DateTime.Now.ToString("yyyy-MM-dd H:mm:ss :: ");
writer.WriteLine(dt + "ERROR: " + error);
Console.WriteLine(dt + "ERROR: " + error);
}
}
and I am doing the following in my Program.
static void Main(string[] args)
{
Logger log = Logger.GetInstance();
log.OpenFile("app.log");
log.LogMessage("Starting App...");
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
或者当您声明
writer
设置 AutoFlush 为 true:编辑: 另外,由于您的类将从多线程访问,因此您应该在写入流之前使用
lock
,因为StreamWriter
实例不是线程安全的,因此:or when you declared the
writer
set AutoFlush to true:Edit: Also since your class will access from multi-thread so you should use
lock
before writing to the stream because theStreamWriter
instance is not thread safe, so:在评论中回答您的问题:为什么建议使用其中之一(Log4Net、NLog)?
顺便说一句,我的 +1 转到 NLog。
To answer your question in comment: Why is it recommended to use one of these (Log4Net, NLog) instead?
BTW, my +1 goes to NLog.