在Azure函数中,如何从代码中访问记录到控制台的信息

yhived7q  于 2023-06-06  发布在  其他
关注(0)|答案(2)|浏览(292)

我有一个Azure函数,每半小时运行一次。我已将日志配置设置为重定向到控制台。

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";

我可以在控制台中看到正在记录“Inin-Correlation-Id”。但是,我不能从代码中访问它。我将输出重定向到一个日志文件,但无法从代码中读取此日志文件,因为它始终在使用中。
如何从代码中访问记录到控制台的信息?

uujelgoq

uujelgoq1#

是的,可以在代码中访问控制台中记录的信息。
为此,你需要做以下事情。
1.在Host.Json文件中,您需要提到“fileLoggingMode”:“永远”

1.需要使用RUN命令从路径中获取日志文件,如下所示。%temp%\LogFiles\Application\Functions。

1.从路径中读取日志文件,并使用以下代码在代码中使用日志或文本。

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:\Users\V-NMOP~1\AppData\Local\Temp\LogFiles\Application\Functions\Host";
            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);
        }
    }

输出

e0bqpujr

e0bqpujr2#

我创建了一个新的logger类

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;
}

然后在函数代码中

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

相关问题