我正在尝试将所有日志详细信息写入文件并使用 API 将其发送到我们的服务器。我为此使用
Serilog
。我做了以下步骤:
已安装
Serilog, Serilog.Extensions.Logging and Serilog.Sinks.File
。
MAUIProgram.cs
添加了以下代码:
public static MauiApp CreateMauiApp()
{
var builder = MauiApp.CreateBuilder();
var logDirectory = Path.Combine(FileSystem.Current.AppDataDirectory, "logs");
var logFilePath = Path.Combine(logDirectory, "log.txt");
// Ensure the directory exists
if (!Directory.Exists(logDirectory))
{
Directory.CreateDirectory(logDirectory);
}
Log.Logger = new LoggerConfiguration()
.WriteTo.File(
path: Path.Combine(logDirectory, "log.txt"),
rollingInterval: RollingInterval.Day,
retainedFileCountLimit: 7, // Keep logs for the last 7 days
restrictedToMinimumLevel: Serilog.Events.LogEventLevel.Information
)
.CreateLogger();
// Check if the file is created right after logging configuration
if (File.Exists(logFilePath))
{
Debug.WriteLine($"Log file created: {logFilePath}");
}
else
{
Debug.WriteLine($"Log file not found at expected location: {logFilePath}");
}
// Add Serilog to the logging system
builder.Logging.AddSerilog();
此处正在创建目录,但未创建
log.txt
文件。我在输出框中得到以下响应:
在预期位置找不到日志文件:/data/user/0/com.companyname.appname/files/logs/log.txt
Log.Information("Test log!");
var logFilePath = Path.Combine(FileSystem.AppDataDirectory, "logs", "log.txt");
Debug.WriteLine("Log file location:>" + logFilePath);
if (File.Exists(logFilePath))
{
var logContent = File.ReadAllText(logFilePath);
Debug.WriteLine("logContent:>>" + logContent);
}
else
{
Debug.WriteLine("Log file not found.");
}
我还在输出框中收到“未找到日志文件”消息。我在这方面遗漏了什么吗?我想将所有日志写入该文件,并且需要将其发送到服务器以调试现实世界的问题。
在预期位置未找到日志文件: /data/user/0/com.companyname.appname/files/logs/log.txt
这是因为您在
rollingInterval: RollingInterval.Day
方法中使用了 new LoggerConfiguration().WriteTo.File
参数,这会将日志文件的名称格式设置为:logyyyyMMdd.txt。在我的测试中它是log20250120.txt。所以你可以删除 rollingInterval: RollingInterval.Day
并使用:
Log.Logger = new LoggerConfiguration()
.WriteTo.File(
path: Path.Combine(logDirectory, "log.txt"),
retainedFileCountLimit: 7, // Keep logs for the last 7 days
restrictedToMinimumLevel: Serilog.Events.LogEventLevel.Information
)
.CreateLogger();
这会将日志文件的名称保留为 log.txt。或者,您也可以在尝试读取日志文件时格式化路径:
var logFilePath =
Path.Combine(FileSystem.Current.AppDataDirectory, "logs", "log"+DateTime.Now.ToString("yyyyMMdd")+".txt");
Debug.WriteLine("Log file location:>" + logFilePath);
if (File.Exists(logFilePath))
{
var logContent = File.ReadAllText(logFilePath);
Debug.WriteLine("logContent:>>" + logContent);
}