このトピックでは、.NET 環境でログを出力および表示する方法について説明します。
ログの出力
関数が標準出力 (stdout) または標準エラー (stderr) に出力した内容は、サービス作成時に指定した Logstore に収集されます。ログを出力するには、fc-dotnet-lib ライブラリの context.Logger メソッドを使用できます。その他のロギングライブラリを使用することも可能です。
context.Logger メソッドを使用してログを出力してください。このメソッドで出力されたログには自動的に RequestId が含まれるため、エラー発生時に特定のログを容易に特定できます。
context.Logger を使用したログの出力
このメソッドで出力される各ログには、時間、RequestId、ログレベルなどの情報が含まれます。以下のコードはその例です。
using System.IO;
using System.Threading.Tasks;
using Aliyun.Serverless.Core;
using Microsoft.Extensions.Logging;
namespace Example
{
public class Hello
{
public async Task<Stream> StreamHandler(Stream input, IFcContext context)
{
IFcLogger logger = context.Logger;
logger.LogInformation("Handle request: {0}", context.RequestId);
logger.LogInformation(string.Format("detail = {0} ", "hello world"));
MemoryStream copy = new MemoryStream();
await input.CopyToAsync(copy);
copy.Seek(0, SeekOrigin.Begin);
return copy;
}
static void Main(string[] args){}
}
}上記のサンプルコードを実行すると、次のログが出力されます。
2022-10-09T07:20:31.024Z 9666a77e-65e7-42a9-b011-************ [INFO] detail = hello worldログレベルの変更
ロガーの EnabledLogLevel プロパティを変更することで、ログレベルを設定できます。ログレベルは、以下の表に示すように、優先度が高い順に並んでいます。
ログレベル | レベル | インターフェイス |
Critical | 5 |
|
Error | 4 |
|
Warning | 3 |
|
Information | 2 |
|
Debug | 1 |
|
Trace | 0 |
|
ログレベルの詳細については、「LogLevel Enum」をご参照ください。
以下のコードはその例です。
using System.IO;
using System.Threading.Tasks;
using Aliyun.Serverless.Core;
using Microsoft.Extensions.Logging;
namespace Example
{
public class Hello
{
public async Task<Stream> StreamHandler(Stream input, IFcContext context)
{
IFcLogger logger = context.Logger;
// Error 以上のレベルのログメッセージを出力します。
logger.EnabledLogLevel = LogLevel.Error;
logger.LogError("console error 1");
logger.LogInformation("console info 1");
logger.LogWarning("console warn 1");
logger.LogDebug("console debug 1");
// Warning 以上のレベルのログメッセージを出力します。
logger.EnabledLogLevel = LogLevel.Warning;
logger.LogError("console error 2");
logger.LogInformation("console info 2");
logger.LogWarning("console warn 2");
logger.LogDebug("console debug 2");
// Information 以上のレベルのログメッセージを出力します。
logger.EnabledLogLevel = LogLevel.Information;
logger.LogInformation("Handle request: {0}", context.RequestId);
MemoryStream copy = new MemoryStream();
await input.CopyToAsync(copy);
copy.Seek(0, SeekOrigin.Begin);
return copy;
}
static void Main(string[] args){}
}
}上記のコードを実行すると、次のログが出力されます。
2022-10-09T07:31:42.644Z 77b8ed17-6760-4877-8a43-b79189****** [ERROR] console error 1
2022-10-09T07:31:42.644Z 77b8ed17-6760-4877-8a43-b79189****** [ERROR] console error 2
2022-10-09T07:31:42.644Z 77b8ed17-6760-4877-8a43-b79189****** [WARNING] console warn 2
2022-10-09T07:31:42.644Z 77b8ed17-6760-4877-8a43-b79189****** [INFO] Handle request: 77b8ed17-6760-4877-8a43-b79189****** ログの表示
関数の実行後、関数の詳細ページにある 呼び出しログ タブでログを確認できます。詳細については、「呼び出しログの表示」をご参照ください。