如何登录C#Azure函数类静态方法



我正在尝试与BlobServiceClient建立一次性连接,即在启动Function App时,每次进行Http调用时都使用该BlobServiceClient。为此,我创建了一个方法

GetBlobSerViceClient()

这将使用blob服务的端点和ManagedIdentity创建一个blobserviceclient。如果这种方法失败了,我需要记录消息,我想知道最好的方法是什么?

这是代码示例:

public static BlobServiceClient storageBlobClient = GetBlobServiceClient();
private static BlobServiceClient GetBlobServiceClient()
{
if(storageEndpoint == null)
{
log.LogInformation($"Storage endpoint is null.");
throw new ArgumentException("Parameter cannot be null", nameof(storageEndpoint));
}
try
{
return new BlobServiceClient(new Uri(storageEndpoint), new DefaultAzureCredential(includeInteractiveCredentials: true));
}catch(Exception ex)
{
//TODO  log message here

throw  ex;
}
}
[FunctionName("Function1")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, ILogger log)
{
\body
}

如果此方法中有任何失败,我将需要记录消息。

解决方法之一是使用Azure SQL保存所有正在记录的消息。

存储数据的步骤:

  1. 创建SQL数据库资源
  2. 连接到Azure SQL数据库
  3. 创建一个可用于存储日志消息的简单表
  4. 复制SQL数据库的连接字符串,然后添加以下代码
// Adding custom code to log messages to the Azure SQL Database
// Creating the connection string
string connectionString = "<YOUR CONNECTION STRING>";
// Using the connection string to open a connection
try {
using(SqlConnection connection = new SqlConnection(connectionString)) {
// Opening a connection
connection.Open();
// Defining the log message and Create Date
var logMessage = $ "{name} has logged in.";
var createDate = DateTime.UtcNow;
// Prepare the SQL Query
var query = $ "INSERT INTO [ApplicationLogs] ([LogMessage],[CreateDate]) VALUES('{logMessage}', '{createDate}')";
// Prepare the SQL command and execute query
SqlCommand command = new SqlCommand(query, connection);
// Open the connection, execute and close connection
if (command.Connection.State == System.Data.ConnectionState.Open) {
command.Connection.Close();
}
command.Connection.Open();
command.ExecuteNonQuery();
}
} 

参考:将消息从Azure函数记录到Azure SQL数据库

最新更新