-
-
Save christiannagel/724a19bbffb0f2de33d9b7d1ef90f40f to your computer and use it in GitHub Desktop.
Using ILogger to log errors and information
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class SampleController | |
{ | |
private readonly ILogger<SampleController> _logger; | |
private readonly HttpClient _httpClient; | |
public SampleController(HttpClient httpClient, ILogger<SampleController> logger) | |
{ | |
_httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient)); | |
_logger = logger ?? throw new ArgumentNullException(nameof(logger)); | |
_logger.LogTrace("ILogger injected into {0}", nameof(SampleController)); | |
} | |
public async Task NetworkRequestSampleAsync(string url) | |
{ | |
try | |
{ | |
_logger.LogInformation(LoggingEvents.Networking, "NetworkRequestSampleAsync started with url {0}", url); | |
string result = await _httpClient.GetStringAsync(url); | |
_logger.LogInformation(LoggingEvents.Networking, "NetworkRequestSampleAsync completed, received {0} characters", result.Length); | |
} | |
catch (Exception ex) | |
{ | |
_logger.LogError(LoggingEvents.Networking, ex, "Error in NetworkRequestSampleAsync, error message: {0}, HResult: {1}", ex.Message, ex.HResult); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment