| | | 1 | | // Licensed to the .NET Foundation under one or more agreements. |
| | | 2 | | // The .NET Foundation licenses this file to you under the MIT license. |
| | | 3 | | |
| | | 4 | | using System; |
| | | 5 | | using Microsoft.Extensions.Logging; |
| | | 6 | | using Xunit; |
| | | 7 | | |
| | | 8 | | namespace Helpers |
| | | 9 | | { |
| | | 10 | | public class XunitLogger : ILogger |
| | | 11 | | { |
| | | 12 | | private readonly ITestOutputHelper _testOutputHelper; |
| | | 13 | | private readonly string _categoryName; |
| | | 14 | | private readonly string _callerMethodName; |
| | | 15 | | |
| | 0 | 16 | | public XunitLogger(ITestOutputHelper testOutputHelper, string categoryName, string callerMethodName) |
| | | 17 | | { |
| | 0 | 18 | | _testOutputHelper = testOutputHelper; |
| | 0 | 19 | | _categoryName = categoryName; |
| | 0 | 20 | | _callerMethodName = callerMethodName; |
| | 0 | 21 | | } |
| | | 22 | | |
| | | 23 | | public IDisposable BeginScope<TState>(TState state) |
| | 0 | 24 | | => NoopDisposable.Instance; |
| | | 25 | | |
| | | 26 | | public bool IsEnabled(LogLevel logLevel) |
| | 0 | 27 | | => true; |
| | | 28 | | |
| | | 29 | | public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exce |
| | | 30 | | { |
| | | 31 | | try |
| | | 32 | | { |
| | 0 | 33 | | _testOutputHelper.WriteLine($"{_categoryName} [{eventId}] {formatter(state, exception)}"); |
| | 0 | 34 | | if (exception != null) |
| | | 35 | | { |
| | 0 | 36 | | _testOutputHelper.WriteLine(exception.ToString()); |
| | | 37 | | } |
| | 0 | 38 | | } |
| | 0 | 39 | | catch (InvalidOperationException e) when (e.Message == "There is no currently active test.") |
| | | 40 | | { |
| | | 41 | | // Swallow exception as this is caused by bug in earlier versions of AspNetCore which would |
| | | 42 | | // write to the logger from the heartbeat code after the host was shut down. |
| | 0 | 43 | | } |
| | 0 | 44 | | } |
| | | 45 | | |
| | | 46 | | private class NoopDisposable : IDisposable |
| | | 47 | | { |
| | 0 | 48 | | public static NoopDisposable Instance = new NoopDisposable(); |
| | | 49 | | public void Dispose() |
| | 0 | 50 | | { } |
| | | 51 | | } |
| | | 52 | | } |
| | | 53 | | } |