日志
更新時間 2024-12-10 11:37:50
最近更新時間: 2024-12-10 11:37:50
分享文章
本文介紹如何在C#運行環境下的日志打印。
打印日志
使用 Serverless.Cf 依賴庫提供方法打印日志
使用庫 Serverless.Cf依賴庫提供的 Logger()方法打印日志,使用該方法打印的每條日志中都包含日志級別、RequestId、時間、文件名和行號等信息。示例代碼如下:
public async Task<Stream> Handler(Stream input, ICfContext context)
{
var str = "Hello world";
byte[] bytetxt = Encoding.UTF8.GetBytes(str);
// 日志打印
context.Logger.LogInformation("Hello log");
MemoryStream output = new MemoryStream();
await input.CopyToAsync(output);
output.Write(bytetxt, 0, bytetxt.Length);
return output;
}
函數被執行后,會輸出以下日志:
2024-07-08 10:32:36.926 xxxxxx [INFO] Hello log
使用 Console.WriteLine 打印日志
您還可以使用 Console.WriteLine()方法打印日志,或者其它寫入到stdout/stderr的日志庫打印日志。示例代碼如下:
public async Task<Stream> Handler(Stream input, ICfContext context)
{
var str = "Hello world";
byte[] bytetxt = Encoding.UTF8.GetBytes(str);
// 控制臺打印
Console.WriteLine("Hello console");
MemoryStream output = new MemoryStream();
await input.CopyToAsync(output);
output.Write(bytetxt, 0, bytetxt.Length);
return output;
}
函數被執行后,會輸出以下日志:
Hello console