.NET 日志记录类无法写入

发布于 2024-11-27 07:32:19 字数 1261 浏览 0 评论 0原文

我刚刚根据我在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

梦晓ヶ微光ヅ倾城 2024-12-04 07:32:20
writer.WriteLine(dt + message);
writer.Flush();

或者当您声明 writer 设置 AutoFlush 为 true:

writer = new StreamWriter(file, true);
writer.AutoFlush = true;

编辑: 另外,由于您的类将从多线程访问,因此您应该在写入流之前使用 lock,因为 StreamWriter 实例不是线程安全的,因此:

private readonly object _writerLocker = new object();

lock (_writerLocker)
{
    writer.WriteLine(dt + "ERROR: " + error);
}
writer.WriteLine(dt + message);
writer.Flush();

or when you declared the writer set AutoFlush to true:

writer = new StreamWriter(file, true);
writer.AutoFlush = true;

Edit: Also since your class will access from multi-thread so you should use lock before writing to the stream because the StreamWriter instance is not thread safe, so:

private readonly object _writerLocker = new object();

lock (_writerLocker)
{
    writer.WriteLine(dt + "ERROR: " + error);
}
孤檠 2024-12-04 07:32:20

在评论中回答您的问题:为什么建议使用其中之一(Log4Net、NLog)?

  • 因为已经调试好了。
  • 因为您可以避免令人讨厌的错误,例如 Jalaal 指出的多线程写入访问。
  • 因为您的日志记录需要更改的那一天(或者您想摆脱日志记录!),您甚至不需要重新编译您的程序:这只是 app.config 中的配置问题。
  • 因为一旦您学会使用这样的日志记录框架,您就可以在其他可能有更高级要求的项目或上下文中轻松地重用它。
  • 因为一旦您意识到它们的功能强大且易于使用,您可能希望添加更强大的日志记录,而无需对其进行编程。

顺便说一句,我的 +1 转到 NLog

To answer your question in comment: Why is it recommended to use one of these (Log4Net, NLog) instead?

  • Because it's already debugged.
  • Because you avoid nasty bugs such as the multithreading write access pointed to by Jalaal.
  • Because the day your logging needs change (or you want to get rid of logging!), you don't even need to recompile your program: It's simply a matter of configuration in your app.config.
  • Because once you have learned to use such a logging framework, you'll be able to re-use it very easily in other projects or contexts, which may have more advanced requirements.
  • Because once you realize how powerful yet easy to use they are, you may want to add more powerful logging without the need to program it.

BTW, my +1 goes to NLog.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文