Skip to content

Instantly share code, notes, and snippets.

@christiannagel
Created November 10, 2018 15:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save christiannagel/724a19bbffb0f2de33d9b7d1ef90f40f to your computer and use it in GitHub Desktop.
Save christiannagel/724a19bbffb0f2de33d9b7d1ef90f40f to your computer and use it in GitHub Desktop.
Using ILogger to log errors and information
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