ProjectArcade

Форк
0
117 строк · 3.8 Кб
1
using System;
2
using System.Threading.Tasks;
3

4
namespace DokanNet.Logging
5
{
6
    /// <summary>
7
    /// Log to the console.
8
    /// </summary>
9
    public class ConsoleLogger : ILogger, IDisposable
10
    {
11
        private readonly string _loggerName;
12
        private readonly System.Collections.Concurrent.BlockingCollection<Tuple<String, ConsoleColor>> _PendingLogs
13
            = new System.Collections.Concurrent.BlockingCollection<Tuple<String, ConsoleColor>>();
14

15
        private readonly Task _WriterTask = null;
16
        private bool _disposed;
17

18
        /// <summary>
19
        /// Initializes a new instance of the <see cref="ConsoleLogger"/> class.
20
        /// </summary>
21
        /// <param name="loggerName">Optional name to be added to each log line.</param>
22
        public ConsoleLogger(string loggerName = "")
23
        {
24
            _loggerName = loggerName;
25
            _WriterTask = Task.Factory.StartNew(() =>
26
            {
27
                foreach (var tuple in _PendingLogs.GetConsumingEnumerable())
28
                {
29
                    WriteMessage(tuple.Item1, tuple.Item2);
30
                }
31
            });
32
        }
33

34
        /// <inheritdoc />        
35
        public bool DebugEnabled { get { return true; } }
36

37
        /// <inheritdoc />
38
        public void Debug(string message, params object[] args)
39
        {
40
            EnqueueMessage(Console.ForegroundColor, message, args);
41
        }
42

43
        /// <inheritdoc />
44
        public void Info(string message, params object[] args)
45
        {
46
            EnqueueMessage(Console.ForegroundColor, message, args);
47
        }
48

49
        /// <inheritdoc />
50
        public void Warn(string message, params object[] args)
51
        {
52
            EnqueueMessage(ConsoleColor.DarkYellow, message, args);
53
        }
54

55
        /// <inheritdoc />
56
        public void Error(string message, params object[] args)
57
        {
58
            EnqueueMessage(ConsoleColor.Red, message, args);
59
        }
60

61
        /// <inheritdoc />
62
        public void Fatal(string message, params object[] args)
63
        {
64
            EnqueueMessage(ConsoleColor.Red, message, args);
65
        }
66

67
        private void EnqueueMessage(ConsoleColor newColor, string message, params object[] args)
68
        {
69
            if (args.Length > 0)
70
                message = string.Format(message, args);
71

72
            _PendingLogs.Add(Tuple.Create(message, newColor));
73
        }
74

75
        private void WriteMessage(string message, ConsoleColor newColor)
76
        {
77
            lock (Console.Out) // we only need this lock because we want to have more than one logger in this version
78
            {
79
                var origForegroundColor = Console.ForegroundColor;
80
                Console.ForegroundColor = newColor;
81
                Console.WriteLine(message.FormatMessageForLogging(true, loggerName: _loggerName));
82
                Console.ForegroundColor = origForegroundColor;
83
            }
84
        }
85

86
        protected virtual void Dispose(bool disposing)
87
        {
88
            if (!_disposed)
89
            {
90
                if (disposing)
91
                {
92
                    // dispose managed state (managed objects)
93
                    _PendingLogs.CompleteAdding();
94
                    _WriterTask.Wait();
95
                }
96

97
                // free unmanaged resources (unmanaged objects) and override finalizer
98
                // set large fields to null
99
                _disposed = true;
100
            }
101
        }
102

103
        // override finalizer only if 'Dispose(bool disposing)' has code to free unmanaged resources
104
        // ~ConsoleLogger()
105
        // {
106
        //     // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
107
        //     Dispose(disposing: false);
108
        // }
109

110
        public void Dispose()
111
        {
112
            // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
113
            Dispose(disposing: true);
114
            GC.SuppressFinalize(this);
115
        }
116
    }
117
}

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.