bovender framework
C# framework that implements MVVM and more
LogFile.cs
1 /* LogFile.cs
2  * part of Bovender framework
3  *
4  * Copyright 2014-2018 Daniel Kraus
5  *
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  * http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  */
18 using System;
19 using System.Collections.Generic;
20 using System.Linq;
21 using System.Text;
22 using NLog;
23 using NLog.Config;
24 using NLog.Targets;
25 using NLog.Targets.Wrappers;
26 
27 namespace Bovender.Logging
28 {
33  public class LogFile
34  {
35  #region Singleton
36 
40  public static Func<LogFile> LogFileProvider { get; set; }
41 
42  public static LogFile Default { get { return _lazy.Value; } }
43 
44  private static readonly Lazy<LogFile> _lazy = new Lazy<LogFile>(
45  () =>
46  {
47  LogFile logFile = null;
48  if (LogFileProvider != null)
49  {
50  logFile = LogFileProvider();
51  }
52  if (logFile == null)
53  {
54  logFile = new LogFile();
55  }
56  return logFile;
57  });
58 
59  #endregion
60 
61  #region Static properties
62 
67  public static bool IsInitializedAndEnabled
68  {
69  get
70  {
71  return _lazy.IsValueCreated && Default.IsFileLoggingEnabled;
72  }
73  }
74 
75  #endregion
76 
77  #region Properties
78 
79  public bool IsFileLoggingEnabled
80  {
81  get
82  {
83  return _fileLoggingEnabled;
84  }
85  set
86  {
87  if (value != _fileLoggingEnabled)
88  {
89  if (value)
90  {
91  EnableFileLogging();
92  }
93  else
94  {
95  DisableFileLogging();
96  }
97  }
98  }
99  }
100 
101  public NLog.LogLevel LogLevel
102  {
103  get
104  {
105  return _logLevel;
106  }
107  set
108  {
109  Logger.Info("LogLevel_set: {0} ==> {1}", _logLevel, value);
110  if (_fileRule != null)
111  {
112  // _fileRule.DisableLoggingForLevel(_logLevel);
113  _fileRule.EnableLoggingForLevels(LogLevel.Trace, value);
114  }
115  _logLevel = value;
116  }
117  }
118 
122  public virtual string LogFolder
123  {
124  get
125  {
126  if (_logFolder == null)
127  {
128  _logFolder = System.IO.Path.GetTempPath();
129  }
130  return _logFolder;
131  }
132  }
133 
137  public string CurrentLogFile
138  {
139  get
140  {
141  if (_currentLogPath == null)
142  {
143  _currentLogPath = System.IO.Path.Combine(LogFolder, LOG_FILE_NAME);
144  }
145  return _currentLogPath;
146  }
147  }
148 
152  public virtual string ArchivedLogsPath
153  {
154  get
155  {
156  if (_archivedLogsPath == null)
157  {
158  _archivedLogsPath = System.IO.Path.Combine(LogFolder, ARCHIVE_FILE_NAME);
159  }
160  return _archivedLogsPath;
161  }
162  }
163 
169  public string CurrentLog
170  {
171  get
172  {
173  try
174  {
175  return System.IO.File.ReadAllText(CurrentLogFile);
176  }
177  catch (System.IO.IOException e)
178  {
179  return e.Message;
180  }
181  }
182  }
183 
190  public bool IsCurrentLogAvailable
191  {
192  get
193  {
194  return System.IO.File.Exists(CurrentLogFile);
195  }
196  }
197 
198  #endregion
199 
200  #region Constructor
201 
202  protected LogFile()
203  {
204  _logLevel = NLog.LogLevel.Info;
205  _config = new LoggingConfiguration();
206  LogManager.Configuration = _config;
207  }
208 
209  #endregion
210 
211  #region Public methods
212 
213  public void ShowFolderInExplorer()
214  {
215  System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(LogFolder));
216  }
217 
218  public void EnableDebugLogging()
219  {
220  if (!_debugLoggingEnabled)
221  {
222  _debugLoggingEnabled = true;
223  DebuggerTarget t = new DebuggerTarget();
224  _config.AddTarget(DEBUG_TARGET, t);
225  _config.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, t));
226  LogManager.ReconfigExistingLoggers();
227  }
228  }
229 
230  #endregion
231 
232  #region Protected properties and methods
233 
234  protected void EnableFileLogging()
235  {
236  _fileLoggingEnabled = true;
237  if (_fileTarget == null)
238  {
239  _fileTarget = new FileTarget();
240  _fileTarget.FileName = CurrentLogFile;
241  _fileTarget.ArchiveFileName = ArchivedLogsPath;
242  _fileTarget.ArchiveNumbering = ArchiveNumberingMode.Date;
243  _fileTarget.ArchiveDateFormat = ARCHIVE_DATE_FORMAT;
244  _fileTarget.ArchiveEvery = FileArchivePeriod.Day;
245  _fileTarget.MaxArchiveFiles = MAX_ARCHIVE_FILES;
246  AsyncTargetWrapper wrapper = new AsyncTargetWrapper(_fileTarget);
247  _config.AddTarget(FILE_TARGET, wrapper);
248  }
249  if (_fileRule == null)
250  {
251  _fileRule = new LoggingRule("*", LogLevel, _fileTarget);
252  }
253  _config.LoggingRules.Add(_fileRule);
254  LogManager.ReconfigExistingLoggers();
255  Logger.Info("===== Begin file logging =====");
256  }
257 
258  protected void DisableFileLogging()
259  {
260  Logger.Info("Disabling file logging");
261  _config.LoggingRules.Remove(_fileRule);
262  LogManager.ReconfigExistingLoggers();
263  _fileLoggingEnabled = false;
264  }
265 
266  #endregion
267 
268  #region Private fields
269 
270  private string _logFolder;
271  private string _currentLogPath;
272  private string _archivedLogsPath;
273  private bool _debugLoggingEnabled;
274  private bool _fileLoggingEnabled;
275  private NLog.LogLevel _logLevel;
276  private LoggingConfiguration _config;
277  private FileTarget _fileTarget;
278  private LoggingRule _fileRule;
279 
280  #endregion
281 
282  #region Private constants
283 
284  private const string FILE_TARGET = "file";
285  private const string DEBUG_TARGET = "debug";
286  private const string LOG_FILE_NAME = "current-log.txt";
287  private const string ARCHIVE_FILE_NAME = "log-{#}.txt";
288  private const string ARCHIVE_DATE_FORMAT = "yyyy-MM-dd";
289  private const int MAX_ARCHIVE_FILES = 7;
290 
291  #endregion
292 
293  #region Class logger
294 
295  private static NLog.Logger Logger { get { return _logger.Value; } }
296 
297  private static readonly Lazy<NLog.Logger> _logger = new Lazy<NLog.Logger>(() => NLog.LogManager.GetCurrentClassLogger());
298 
299  #endregion
300  }
301 }
Provides logging to file and to the debug console; wraps NLog configuration and targets.
Definition: LogFile.cs:33