admin管理员组

文章数量:1123589

I am trying to write all log details to a file and send that to our server using an API. I am using Serilog for this. I did below steps:

  1. Installed Serilog, Serilog.Extensions.Logging and Serilog.Sinks.File.

  2. MAUIProgram.cs added below code:

        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();

Here the Directory is creating, but the log.txt file is not creating. I am getting below response in output box:

Log file not found at expected location: /data/user/0/companyname.appname/files/logs/log.txt

  1. I did a test log like below in another page like below.
       Log.Information("Test log!");
  1. Finally I tried reading the log details like below to send it to my server.
        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.");
        }

Here also I am getting "Log file not found" message in output box. Am I missing anything in this? I want to write all the logs to that file and I need to send it to the server for debugging the real world issues.

本文标签: MAUI Serilog log file is not creatingStack Overflow