forked from benrhughes/todotxt.net
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLog.cs
81 lines (67 loc) · 2.24 KB
/
Log.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
using System;
using System.IO;
using System.Text;
using System.Threading;
using CommonExtensions;
namespace ToDoLib
{
public enum LogLevel
{
Error,
Debug
}
public static class Log
{
public static LogLevel LogLevel { get; set; }
public static string _logFile;
public static string LogFile
{
get
{
if (_logFile == null)
{
_logFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"Hughesoft", "todotxt.exe", "log.txt");
}
return _logFile;
}
set
{
_logFile = value;
}
}
public static void Debug(string msg, params string[] values)
{
if (LogLevel == LogLevel.Debug)
Write(msg, values);
}
public static void Error(string msg, Exception ex)
{
Error(msg + Environment.NewLine + ex.ToString());
}
public static void Error(string msg, params string[] values)
{
if (LogLevel == LogLevel.Debug || LogLevel == LogLevel.Error)
Write(msg, values);
}
private static void Write(string msg, params string[] values)
{
if (!values.IsNullOrEmpty())
msg = string.Format(msg, values);
msg = "[" + DateTime.Now.ToString() + "] " + msg + Environment.NewLine + Environment.NewLine;
var logFileDir = Path.GetDirectoryName(LogFile);
if (!Directory.Exists(logFileDir))
Directory.CreateDirectory(logFileDir);
// perhaps a little heavy handed, but we want to make sure no other instances of todotxt.net are
// writing to the log file at the same time
using (var m = new Mutex(true, LogFile.Replace(Path.DirectorySeparatorChar, '_')))
{
if (m.WaitOne(10000))
File.AppendAllText(LogFile, msg, Encoding.UTF8);
else
throw new Exception("Could not obtain lock on " + LogFile);
m.ReleaseMutex();
}
}
}
}