microsoft/teams.net

Public

mirrored fromhttps://github.com/microsoft/teams.netAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
feat/a365-mcp

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

core/src/Microsoft.Teams.Apps/ContextLogger.cs

73lines · modecode

1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
4using Microsoft.Extensions.Logging;
5
6namespace Microsoft.Teams.Apps;
7
8/// <summary>
9/// Provides backward-compatible logging methods (<c>.Info()</c>, <c>.Error()</c>, <c>.Debug()</c>, <c>.Warn()</c>)
10/// that delegate to an underlying <see cref="ILogger"/> instance.
11/// </summary>
12/// <param name="logger">The underlying logger to delegate to.</param>
13public class ContextLogger(ILogger logger)
14{
15 /// <summary>
16 /// Gets the underlying <see cref="ILogger"/> instance.
17 /// </summary>
18 public ILogger Logger { get; } = logger;
19
20 /// <summary>
21 /// Logs a message at the <see cref="LogLevel.Information"/> level.
22 /// </summary>
23 /// <param name="args">The message arguments. The first string argument is used as the message template.</param>
24 public void Info(params object?[] args)
25 {
26 ArgumentNullException.ThrowIfNull(args);
27 if (!Logger.IsEnabled(LogLevel.Information)) return;
28 Logger.LogInformation("{Message}", FormatArgs(args));
29 }
30
31 /// <summary>
32 /// Logs a message at the <see cref="LogLevel.Error"/> level.
33 /// </summary>
34 /// <param name="args">The message arguments. The first string argument is used as the message template.</param>
35 public void Error(params object?[] args)
36 {
37 ArgumentNullException.ThrowIfNull(args);
38 if (!Logger.IsEnabled(LogLevel.Error)) return;
39 Logger.LogError("{Message}", FormatArgs(args));
40 }
41
42 /// <summary>
43 /// Logs a message at the <see cref="LogLevel.Debug"/> level.
44 /// </summary>
45 /// <param name="args">The message arguments. The first string argument is used as the message template.</param>
46 public void Debug(params object?[] args)
47 {
48 ArgumentNullException.ThrowIfNull(args);
49 if (!Logger.IsEnabled(LogLevel.Debug)) return;
50 Logger.LogDebug("{Message}", FormatArgs(args));
51 }
52
53 /// <summary>
54 /// Logs a message at the <see cref="LogLevel.Warning"/> level.
55 /// </summary>
56 /// <param name="args">The message arguments. The first string argument is used as the message template.</param>
57 public void Warn(params object?[] args)
58 {
59 ArgumentNullException.ThrowIfNull(args);
60 if (!Logger.IsEnabled(LogLevel.Warning)) return;
61 Logger.LogWarning("{Message}", FormatArgs(args));
62 }
63
64 private static string FormatArgs(object?[] args)
65 {
66 return args.Length switch
67 {
68 0 => string.Empty,
69 1 => args[0]?.ToString() ?? string.Empty,
70 _ => string.Join(" ", args.Select(a => a?.ToString() ?? "null"))
71 };
72 }
73}