-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathLogger.cs
82 lines (73 loc) · 2.17 KB
/
Logger.cs
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
using System;
using System.IO;
using System.Threading;
// Copyright (c) 2016 Ben Spiller.
namespace BetterReminders
{
/// <summary>
/// A trivial class for diagnostic logging to a text file in usuer=profiledir/AppData/Local/OutlookBetterReminders;
/// also writes to the standard Diagnostics.Trace logger as a backup, though that's not so easy to use from an addin.
///
/// Since most people won't want a log, we only generate one if the file already exists
///
/// Currently the log level is not configurable, but as we wipe the log on startup we should never generate enough output to be a problem.
/// </summary>
class Logger
{
public static Logger GetLogger() { return instance; }
private static Logger instance = new Logger();
private StreamWriter sw = null;
private Logger()
{
try
{
string logpath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + @"\OutlookBetterReminders\better-reminders.log";
if (!File.Exists(logpath))
{
// we still have diagnotics.trace logging
Info("Not writing a .log file as " + logpath + " does not exist");
return;
}
// create a new text file, overwrite existing
sw = new StreamWriter(new FileStream(logpath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite))
{
AutoFlush = true
};
} catch (Exception ex)
{
Error("Failed to setup logger: ", ex);
}
}
public void Error(string msg, Exception ex)
{
log("ERROR", msg + ex.ToString() + "\n" + ex.StackTrace);
}
public void Error(string msg)
{
log("ERROR", msg);
}
public void Info(string msg)
{
log("INFO", msg);
}
public void Debug(string msg)
{
log("DEBUG", msg);
}
public Boolean Enabled
{
get { return sw != null; }
}
private void log(string level, string msg)
{
System.Diagnostics.Trace.TraceInformation("BetterReminders - "+level+" - "+msg);
if (sw != null)
sw.WriteLine("[" + Thread.CurrentThread.Name + " " + DateTime.Now + "] "+level+" - " + msg);
}
public void Shutdown()
{
sw.Close();
sw = null;
}
}
}