在 Azure 函数 V2 中用 ILogger 替换 TraceWriter
Replace TraceWriter With ILogger in azure function V2
我们正在尝试将 azure 函数迁移到 sdk.functions 1.0.21,并将所有内容升级到 3.0.0-rc1。控制台提示我们 TraceWriter
已过时,改用 ILogger
。但是,我们一直 运行 问题。
这是我正在使用的代码:
code.cs
:
public static async Task Run(Message queueItem, ILogger log, ExecutionContext context){
using (var scope = Resolver.CreateScope())
{
var timer = new Stopwatch();
try
{
var resolver = scope.ServiceProvider;
logger = resolver.GetService<IBestLogger>().WithInvocationId(context);
client = resolver.GetService<IServiceBusFactory>().GetClient(logger, _queue, _failedQueue);
auditRepository = resolver.GetService<ITplTransactionAuditRepository>();
asnService = resolver.GetService<IAsnService>();
var sfWmsService = resolver.GetService<ISnapfulfilWmsService>();
logger.CreateContext($"{_queue} process is started for message id.").WithServiceBusMessage(queueItem).LogInformation();
}
}
catch (Exception ex2)
{
errorMessage = $"Unable to set record to Error status for message id {queueItem.MessageId} in {_queue}.";
if (logger == null)
log.Error(errorMessage);
else
logger.CreateContext(errorMessage, ex2).LogError();
}
}
function.json
:
{
"bindings": [
{
"queueName": "%InvoiceDetailCalculate_Queue%",
"connection": "ServiceBus_Connection",
"name": "queueItem",
"type": "serviceBusTrigger",
"direction": "in",
"accessRights": "manage"
}
],
"disabled": false
}
Run.csx
:
#r "../bin/Best.Billing.Functions.dll"
#r "../bin/Best.Libraries.Utility.dll"
public static async void Run(Message queueItem, ILogger log, ExecutionContext context)
{
try
{
Code.Run(queueItem, log, context).Wait();
}
catch (Exception ex)
{
ex.Rethrow();
}
}
错误信息是:
Run.csx(4,26): warning AF008: This method has the async keyword but it returns void
Run.csx(4,30): error CS0246: The type or namespace name 'Message' could not be found (are you missing a using directive or an assembly reference?)
Run.csx(8,9): error CS0103: The name 'Code' does not exist in the current context
Run.csx(12,13): error CS1061: 'ILogger' does not contain a definition for 'Error' and no extension method 'Error' accepting a first argument of type 'ILogger' could be found (are you missing a using directive or an assembly reference?)
Run.csx(13,12): error CS1061: 'Exception' does not contain a definition for 'Rethrow' and no extension method 'Rethrow' accepting a first argument of type 'Exception' could be found (are you missing a using directive or an assembly reference?)
Run.csx(4,26): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.
Function compilation error
你需要做两件事:
首先,添加对Ilogger
的引用。
在函数的顶部,添加一个 using Microsoft.Extensions.Logging;
语句。
其次,您需要使用 Ilogger
方法名称。将 log.Error(errorMessage)
更改为 log.LogError(errorMessage)
。您需要在 调用 TraceWriter 方法的任何地方执行此操作。
这是a full list of the newer ILogger methods。
例如,下面是使用 Ilogger
而不是 Tracewriter
的完全实现的 Azure Function v2 .NET 标准:
using System.IO;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Azure.WebJobs.Host;
using Newtonsoft.Json;
using Microsoft.Extensions.Logging;
namespace FunctionApp1
{
public static class Function1
{
[FunctionName("Function1")]
public static 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 = new StreamReader(req.Body).ReadToEnd();
dynamic data = JsonConvert.DeserializeObject(requestBody);
name = name ?? data?.name;
return name != null
? (ActionResult)new OkObjectResult($"Hello, {name}")
: new BadRequestObjectResult("Please pass a name on the query string or in the request body");
}
}
}
我们正在尝试将 azure 函数迁移到 sdk.functions 1.0.21,并将所有内容升级到 3.0.0-rc1。控制台提示我们 TraceWriter
已过时,改用 ILogger
。但是,我们一直 运行 问题。
这是我正在使用的代码:
code.cs
:
public static async Task Run(Message queueItem, ILogger log, ExecutionContext context){
using (var scope = Resolver.CreateScope())
{
var timer = new Stopwatch();
try
{
var resolver = scope.ServiceProvider;
logger = resolver.GetService<IBestLogger>().WithInvocationId(context);
client = resolver.GetService<IServiceBusFactory>().GetClient(logger, _queue, _failedQueue);
auditRepository = resolver.GetService<ITplTransactionAuditRepository>();
asnService = resolver.GetService<IAsnService>();
var sfWmsService = resolver.GetService<ISnapfulfilWmsService>();
logger.CreateContext($"{_queue} process is started for message id.").WithServiceBusMessage(queueItem).LogInformation();
}
}
catch (Exception ex2)
{
errorMessage = $"Unable to set record to Error status for message id {queueItem.MessageId} in {_queue}.";
if (logger == null)
log.Error(errorMessage);
else
logger.CreateContext(errorMessage, ex2).LogError();
}
}
function.json
:
{
"bindings": [
{
"queueName": "%InvoiceDetailCalculate_Queue%",
"connection": "ServiceBus_Connection",
"name": "queueItem",
"type": "serviceBusTrigger",
"direction": "in",
"accessRights": "manage"
}
],
"disabled": false
}
Run.csx
:
#r "../bin/Best.Billing.Functions.dll"
#r "../bin/Best.Libraries.Utility.dll"
public static async void Run(Message queueItem, ILogger log, ExecutionContext context)
{
try
{
Code.Run(queueItem, log, context).Wait();
}
catch (Exception ex)
{
ex.Rethrow();
}
}
错误信息是:
Run.csx(4,26): warning AF008: This method has the async keyword but it returns void
Run.csx(4,30): error CS0246: The type or namespace name 'Message' could not be found (are you missing a using directive or an assembly reference?)
Run.csx(8,9): error CS0103: The name 'Code' does not exist in the current context
Run.csx(12,13): error CS1061: 'ILogger' does not contain a definition for 'Error' and no extension method 'Error' accepting a first argument of type 'ILogger' could be found (are you missing a using directive or an assembly reference?)
Run.csx(13,12): error CS1061: 'Exception' does not contain a definition for 'Rethrow' and no extension method 'Rethrow' accepting a first argument of type 'Exception' could be found (are you missing a using directive or an assembly reference?)
Run.csx(4,26): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.
Function compilation error
你需要做两件事:
首先,添加对
Ilogger
的引用。在函数的顶部,添加一个
using Microsoft.Extensions.Logging;
语句。其次,您需要使用
Ilogger
方法名称。将log.Error(errorMessage)
更改为log.LogError(errorMessage)
。您需要在 调用 TraceWriter 方法的任何地方执行此操作。
这是a full list of the newer ILogger methods。
例如,下面是使用 Ilogger
而不是 Tracewriter
的完全实现的 Azure Function v2 .NET 标准:
using System.IO;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Azure.WebJobs.Host;
using Newtonsoft.Json;
using Microsoft.Extensions.Logging;
namespace FunctionApp1
{
public static class Function1
{
[FunctionName("Function1")]
public static 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 = new StreamReader(req.Body).ReadToEnd();
dynamic data = JsonConvert.DeserializeObject(requestBody);
name = name ?? data?.name;
return name != null
? (ActionResult)new OkObjectResult($"Hello, {name}")
: new BadRequestObjectResult("Please pass a name on the query string or in the request body");
}
}
}