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时。例如在类SqlRead中的信息,它不会被添加到在类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();
}
}
}
您的原始代码(附带我的注释):
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();
}
}
}
删除所有其他类中的CloseAndFlush()
调用。