如何在多个类中使用一个与serilog一起使用一个logfile

发布于 2025-02-06 03:08:03 字数 1813 浏览 4 评论 0原文

internal static class Program
{
    /// <summary>
    ///  The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        // To customize application configuration such as set high DPI settings or default font,
        // see https://aka.ms/applicationconfiguration.
        ApplicationConfiguration.Initialize();
        Application.Run(new Form1());

        Log.Logger = new LoggerConfiguration()
            .MinimumLevel.Debug()
            .WriteTo.File("logs/ConverterLog.txt", rollingInterval: RollingInterval.Day)
            .CreateLogger();
        Log.Information("Program Startup");
    }
}

我正在尝试将Serilog实现到我的Windows表单应用程序中,但我不知道如何登录多个类以写入同一文件。例如,当我使用log.formertion时,例如在类SQLREAD中,它不会将其添加到类程序中配置的logFile中。

class SqlRead
{
    public void Password(string sqlConnectionString, List<SqlInformation> sqlInformationList)
    {
        string sqlQuerySelect = "SELECT Login, Password FROM Users Order by Login";
        using var sqlConn = new SqlConnection(sqlConnectionString);
        using var sqlCmdSelect = new SqlCommand(sqlQuerySelect, sqlConn);
        try
        {
            sqlConn.Open();
            using SqlDataReader sqlReader = sqlCmdSelect.ExecuteReader();
            while (sqlReader.Read())
            {
                sqlInformationList.Add(new SqlInformation() { Username = sqlReader[0].ToString(), Password = sqlReader[1].ToString() });
            }
            sqlReader.Close();
            Log.Information("SQL data successfully read");
        }
        catch (SqlException e)
        {
            MessageBox.Show(e.Message);
            Log.Error(e.Message);
        }
        finally
        {
            Log.CloseAndFlush();
        }
    }
}
internal static class Program
{
    /// <summary>
    ///  The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        // To customize application configuration such as set high DPI settings or default font,
        // see https://aka.ms/applicationconfiguration.
        ApplicationConfiguration.Initialize();
        Application.Run(new Form1());

        Log.Logger = new LoggerConfiguration()
            .MinimumLevel.Debug()
            .WriteTo.File("logs/ConverterLog.txt", rollingInterval: RollingInterval.Day)
            .CreateLogger();
        Log.Information("Program Startup");
    }
}

I am trying to implement Serilog into my Windows Forms application but I can't figure out how to log over multiple classes to write into the same file. When I use Log.Information for example in the class SqlRead, it does not get added to logfile which is configured in the class Program.

class SqlRead
{
    public void Password(string sqlConnectionString, List<SqlInformation> sqlInformationList)
    {
        string sqlQuerySelect = "SELECT Login, Password FROM Users Order by Login";
        using var sqlConn = new SqlConnection(sqlConnectionString);
        using var sqlCmdSelect = new SqlCommand(sqlQuerySelect, sqlConn);
        try
        {
            sqlConn.Open();
            using SqlDataReader sqlReader = sqlCmdSelect.ExecuteReader();
            while (sqlReader.Read())
            {
                sqlInformationList.Add(new SqlInformation() { Username = sqlReader[0].ToString(), Password = sqlReader[1].ToString() });
            }
            sqlReader.Close();
            Log.Information("SQL data successfully read");
        }
        catch (SqlException e)
        {
            MessageBox.Show(e.Message);
            Log.Error(e.Message);
        }
        finally
        {
            Log.CloseAndFlush();
        }
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

梦在夏天 2025-02-13 03:08:03

您的原始代码(带有我的评论):

internal static class Program
{
    [STAThread]
    static void Main()
    {
        ApplicationConfiguration.Initialize();
        Application.Run(new Form1()); // <-- This will block until you exit.

        // Only then (AFTER the main window closes) the Logger will be 
        // actually configured ...
        Log.Logger = new LoggerConfiguration()
            .MinimumLevel.Debug()
            .WriteTo.File("logs/ConverterLog.txt", rollingInterval: RollingInterval.Day)
            .CreateLogger();
        // ... and this line will be logged.
        Log.Information("Program Startup");
        // As you see: No other class has even a chance to log anything.
    }
}

我认为应该有效:

internal static class Program
{
    [STAThread]
    static void Main()
    {
        // Configure Logging _first_.
        Log.Logger = new LoggerConfiguration()
            .MinimumLevel.Debug()
            .WriteTo.File("logs/ConverterLog.txt", rollingInterval: RollingInterval.Day)
            .CreateLogger();
        
        try
        {
            Log.Information("Program Startup");

            ApplicationConfiguration.Initialize();
            Application.Run(new Form1()); // <-- This will block until you exit.
      
            Log.Information("Program Exit");
        }
        finally
        {
            Log.CloseAndFlush();
        }
    }
}

在所有其他类中删除任何colleandflush()调用。

Your original code (with comments from me):

internal static class Program
{
    [STAThread]
    static void Main()
    {
        ApplicationConfiguration.Initialize();
        Application.Run(new Form1()); // <-- This will block until you exit.

        // Only then (AFTER the main window closes) the Logger will be 
        // actually configured ...
        Log.Logger = new LoggerConfiguration()
            .MinimumLevel.Debug()
            .WriteTo.File("logs/ConverterLog.txt", rollingInterval: RollingInterval.Day)
            .CreateLogger();
        // ... and this line will be logged.
        Log.Information("Program Startup");
        // As you see: No other class has even a chance to log anything.
    }
}

What I think should work:

internal static class Program
{
    [STAThread]
    static void Main()
    {
        // Configure Logging _first_.
        Log.Logger = new LoggerConfiguration()
            .MinimumLevel.Debug()
            .WriteTo.File("logs/ConverterLog.txt", rollingInterval: RollingInterval.Day)
            .CreateLogger();
        
        try
        {
            Log.Information("Program Startup");

            ApplicationConfiguration.Initialize();
            Application.Run(new Form1()); // <-- This will block until you exit.
      
            Log.Information("Program Exit");
        }
        finally
        {
            Log.CloseAndFlush();
        }
    }
}

Remove any CloseAndFlush() calls in all other classes.

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