skip to Main Content

I have an Azure Function that runs every half hour. I have set the log configuration to redirect to the console.

    Configuration.Default.Logger.Level = 
    PureCloudPlatform.Client.V2.Client.LogLevel.LTrace;
    Configuration.Default.Logger.Format = LogFormat.JSON;
    Configuration.Default.Logger.LogRequestBody = true;
    Configuration.Default.Logger.LogResponseBody = true;
    Configuration.Default.Logger.LogToConsole = true;
    Configuration.Default.Logger.LogFilePath = tempFolder+"\dotnetsdk.log";

I can see in the console that "Inin-Correlation-Id" is being logged. However, I cannot get access to this from within the code. I redirect the output to a log file but I cannot read this log file from the code as it is always in use.

How do I get access to the information logged to the console from within the code?

2

Answers


  1. Chosen as BEST ANSWER

    I create a new logger class

    using System.IO;
    
    public class ConsoleToFileLogger : TextWriter
    {
        private readonly TextWriter _consoleWriter;
        private readonly string _logFilePath;
    
        public ConsoleToFileLogger(string logFilePath)
        {
            _consoleWriter = Console.Out;
            _logFilePath = logFilePath;
        }
    
        public override void Write(char value)
        {
            _consoleWriter.Write(value); // Write to the console
    
            using (var writer = new StreamWriter(_logFilePath, true))
            {
                writer.Write(value); // Write to the file
            }
        }
    
        public override void Flush()
        {
            _consoleWriter.Flush();
        }
    
        public override Encoding Encoding => _consoleWriter.Encoding;
    }
    
    

    and then in the function code

     var logFilePath = "<path_to_log_file>";
    
            // Create an instance of the custom logger
            var consoleToFileLogger = new ConsoleToFileLogger(logFilePath);
    
            // Redirect the console output to the file
            Console.SetOut(consoleToFileLogger);
    
           
    
            // Make sure to flush and close the logger when you're done
            consoleToFileLogger.Flush();
            consoleToFileLogger.Close();
    

  2. Yes, the logged information in the console from can be accessed within the code.

    For this you need to do the below things.

    1. In Host.Json file you need to mention "fileLoggingMode": "always".

    enter image description here

    1. Need to take the log file from the path using RUN command as below. "%temp%LogFilesApplicationFunctions".

    enter image description here

    1. Read the log file from the path and use the logs or text in your code by using the below code.

    enter image description here

    public static class Function1
        {
            [FunctionName("Function1")]
            public static async Task<IActionResult> Run(
                [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
                ILogger log)
            {
                log.LogInformation("C# HTTP trigger function processed a request.");
    
                string name = req.Query["name"];
    
                string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
                dynamic data = JsonConvert.DeserializeObject(requestBody);
                name = name ?? data?.name;
    
                string responseMessage = string.IsNullOrEmpty(name)
                    ? "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."
                    : $"Hello, {name}. This HTTP triggered function executed successfully.";
    
                string folder_Path = @"C:UsersV-NMOP~1AppDataLocalTempLogFilesApplicationFunctionsHost";
                string[] Myfiles = Directory.GetFiles(folder_Path);
                string recent_File = Myfiles.OrderByDescending(f => new FileInfo(f).LastWriteTime).FirstOrDefault();
                string txt = File.ReadAllText(recent_File);
    
                return new OkObjectResult(txt);
            }
        }
    

    Output

    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search