summaryrefslogtreecommitdiffstats
path: root/win/CS/HandBrake.ApplicationServices/Services/Logging/LogService.cs
blob: b0292ca318a06358aeb5424aa89ab6b1878dd296 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="LogService.cs" company="HandBrake Project (http://handbrake.fr)">
//   This file is part of the HandBrake source code - It may be used under the terms of the GNU General Public License.
// </copyright>
// <summary>
//   The log service.
//   For now, this is just a simple logging service but we could provide support for a formal logging library later.
//   Also, we can consider providing the UI layer with more functional logging. (i.e levels, time/date, highlighting etc)
//   The Interop Classes are not very OO friendly, so this is going to be a static class.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace HandBrake.ApplicationServices.Services.Logging
{
    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.IO;
    using System.Text;

    using HandBrake.ApplicationServices.Services.Logging.EventArgs;
    using HandBrake.ApplicationServices.Services.Logging.Interfaces;
    using HandBrake.ApplicationServices.Services.Logging.Model;

    /// <summary>
    /// The log helper.
    /// </summary>
    public class LogService : ILog
    {
        // TODO List.
        // Maybe make the event weak?
        // Make this class Thread Safe.
        private static ILog loggerInstance;
        private readonly object lockObject = new object();
        private readonly object FileWriterLock = new object();
        private readonly StringBuilder logBuilder = new StringBuilder();
 
        private LogLevel currentLogLevel = LogLevel.Error;
        private bool isLoggingEnabled;
        private List<LogMessage> logMessages = new List<LogMessage>(); 
        private long messageIndex;
        private string diskLogPath;
        private bool deleteLogFirst;
        private bool isDiskLoggingEnabled;
        private StreamWriter fileWriter;
        private string logHeader;

        /// <summary>
        /// Fires when a new QueueTask starts
        /// </summary>
        public event EventHandler<LogEventArgs> MessageLogged;

        /// <summary>
        /// The log reset event
        /// </summary>
        public event EventHandler LogReset;

        /// <summary>
        /// Gets the log messages.
        /// </summary>
        public IEnumerable<LogMessage> LogMessages
        {
            get
            {
                lock (this.lockObject)
                {
                    return this.logMessages;
                }
            }
        }

        /// <summary>
        /// Gets the Activity Log as a string.
        /// </summary>
        public string ActivityLog
        {
            get
            {
                lock (this.lockObject)
                {
                    return this.logBuilder.ToString();
                }
            }
        }

        /// <summary>
        /// Log message.
        /// </summary>
        /// <param name="content">
        /// The content.
        /// </param>
        /// <param name="type">
        /// The type.
        /// </param>
        /// <param name="level">
        /// The level.
        /// </param>
        public void LogMessage(string content, LogMessageType type, LogLevel level)
        {
            if (!this.isLoggingEnabled)
            {
                return;
            }

            if (level >= this.currentLogLevel)
            {
                return;
            }

            LogMessage msg = new LogMessage(content, type, level, this.messageIndex);
            lock (this.lockObject)
            {
                this.messageIndex = this.messageIndex + 1;   
                this.logMessages.Add(msg);
                this.logBuilder.AppendLine(msg.Content);
                this.LogMessageToDisk(msg);

                if (this.logMessages.Count > 50000)
                {
                    this.messageIndex = this.messageIndex + 1;
                    msg = new LogMessage(
                            "Log Service Pausing. Too Many Log messages. This may indicate a problem with your encode.",
                            LogMessageType.Application,
                            LogLevel.Error,
                            this.messageIndex);
                    this.logMessages.Add(msg);
                    this.logBuilder.AppendLine(msg.Content);
                    this.LogMessageToDisk(msg);

                    this.Disable();
                }
            }

            this.OnMessageLogged(msg); // Must be outside lock to be thread safe. 
        }

        /// <summary>
        /// Gets an shared instance of the logger. Logging is enabled by default
        /// You can turn it off by calling Disable() if you don't want it.
        /// </summary>
        /// <returns>
        /// An instance of this logger.
        /// </returns>
        public static ILog GetLogger()
        {
            return loggerInstance ?? (loggerInstance = new LogService());
        }

        /// <summary>
        /// The set log level. Default: Info.
        /// </summary>
        /// <param name="level">
        /// The level.
        /// </param>
        public void SetLogLevel(LogLevel level)
        {
            this.currentLogLevel = level;
        }

        /// <summary>
        /// The enable.
        /// </summary>
        public void Enable()
        {
            this.isLoggingEnabled = true;
        }

        /// <summary>
        /// Enable Logging to Disk
        /// </summary>
        /// <param name="logFile">
        /// The log file to write to.
        /// </param>
        /// <param name="deleteCurrentLogFirst">
        /// Delete the current log file if it exists.
        /// </param>
        public void EnableLoggingToDisk(string logFile, bool deleteCurrentLogFirst)
        {
            if (this.isDiskLoggingEnabled)
            {
                throw new Exception("Disk Logging already enabled!");
            }

            try
            {
                if (!Directory.Exists(Path.GetDirectoryName(logFile)))
                {
                    throw new Exception("Log Directory does not exist. This service will not create it for you!");
                }

                if (deleteCurrentLogFirst && File.Exists(logFile))
                {
                    File.Delete(logFile);
                }

                this.diskLogPath = logFile;
                this.isDiskLoggingEnabled = true;
                this.deleteLogFirst = deleteCurrentLogFirst;

                lock (this.FileWriterLock)
                {
                    this.fileWriter = new StreamWriter(logFile) { AutoFlush = true };
                }
            }
            catch (Exception exc)
            {
                this.LogMessage("Failed to Initialise Disk Logging. " + Environment.NewLine + exc, LogMessageType.Application, LogLevel.Error);

                if (this.fileWriter != null)
                {
                    lock (this.FileWriterLock)
                    {
                        this.fileWriter.Flush();
                        this.fileWriter.Close();
                        this.fileWriter.Dispose();
                    }
                }
            }
        }

        /// <summary>
        /// The setup log header.
        /// </summary>
        /// <param name="header">
        /// The header.
        /// </param>
        public void SetupLogHeader(string header)
        {
            this.logHeader = header;
            this.LogMessage(header, LogMessageType.Application, LogLevel.Info);
        }

        /// <summary>
        /// The disable.
        /// </summary>
        public void Disable()
        {
            this.isLoggingEnabled = false;
        }

        /// <summary>
        /// Clear the log messages collection.
        /// </summary>
        public void Reset()
        {
            lock (this.lockObject)
            {
                this.logMessages.Clear();
                this.logBuilder.Clear();
                this.messageIndex = 0;
               
                try
                {
                    lock (this.FileWriterLock)
                    {
                        if (this.fileWriter != null)
                        {
                            this.fileWriter.Flush();
                            this.fileWriter.Close();
                            this.fileWriter.Dispose();
                        }

                        this.fileWriter = null;
                    }
                }
                catch (Exception exc)
                {
                    Debug.WriteLine(exc);
                }

                if (this.fileWriter == null)
                {
                    this.isDiskLoggingEnabled = false;
                    this.EnableLoggingToDisk(this.diskLogPath, this.deleteLogFirst);
                }

                if (!string.IsNullOrEmpty(this.logHeader))
                {
                    this.SetupLogHeader(this.logHeader);
                }

                this.OnLogReset();
            }
        }

        /// <summary>
        /// Helper method for logging content to disk
        /// </summary>
        /// <param name="msg">
        /// Log message to write.
        /// </param>
        private void LogMessageToDisk(LogMessage msg)
        {
            if (!this.isDiskLoggingEnabled)
            {
                return;
            }

            try
            {
                lock (this.FileWriterLock)
                {
                    if (this.fileWriter != null && this.fileWriter.BaseStream.CanWrite)
                    {
                        this.fileWriter.WriteLine(msg.Content);
                    }
                }
            }
            catch (Exception exc)
            {
                Debug.WriteLine(exc); // This exception doesn't warrent user interaction, but it should be logged
            }
        }

        /// <summary>
        /// Called when a log message is created.
        /// </summary>
        /// <param name="msg">
        /// The Log Message
        /// </param>
        protected virtual void OnMessageLogged(LogMessage msg)
        {
            var onMessageLogged = this.MessageLogged;
            if (onMessageLogged != null)
            {
                onMessageLogged.Invoke(this, new LogEventArgs(msg));
            }
        }

        /// <summary>
        /// Shutdown and Dispose of the File Writer.
        /// </summary>
        protected void ShutdownFileWriter()
        {
            try
            {
                lock (this.FileWriterLock)
                {
                    if (this.fileWriter != null)
                    {
                        this.fileWriter.Flush();
                        this.fileWriter.Close();
                        this.fileWriter.Dispose();
                    }

                    this.fileWriter = null;
                }
            }
            catch (Exception exc)
            {
                Debug.WriteLine(exc); // This exception doesn't warrent user interaction, but it should be logged
            }
        }

        // Trigger the Event to notify any subscribers that the log has been reset.
        protected virtual void OnLogReset()
        {
            this.LogReset?.Invoke(this, System.EventArgs.Empty);
        }
    }
}