/
StreamLogger.cs
58 lines (49 loc) · 1.85 KB
/
StreamLogger.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
using System;
using System.IO;
using UnityEngine;
namespace ModuleManager.Logging
{
public class StreamLogger : IBasicLogger, IDisposable
{
private const string DATETIME_FORMAT_STRING = "yyyy-MM-dd HH:mm:ss.fff";
private readonly Stream stream;
private readonly StreamWriter streamWriter;
private bool disposed = false;
public StreamLogger(Stream stream)
{
this.stream = stream ?? throw new ArgumentNullException(nameof(stream));
if (!stream.CanWrite) throw new ArgumentException("must be writable", nameof(stream));
streamWriter = new StreamWriter(stream);
}
public void Log(LogType logType, string message)
{
if (disposed) throw new InvalidOperationException("Object has already been disposed");
string prefix;
if (logType == LogType.Log)
prefix = "LOG";
else if (logType == LogType.Warning)
prefix = "WRN";
else if (logType == LogType.Error)
prefix = "ERR";
else if (logType == LogType.Assert)
prefix = "AST";
else if (logType == LogType.Exception)
prefix = "EXC";
else
prefix = "UNK";
streamWriter.WriteLine("[{0} {1}] {2}", prefix, DateTime.Now.ToString(DATETIME_FORMAT_STRING), message);
}
public void Exception(string message, Exception exception)
{
if (!string.IsNullOrEmpty(message)) message += ": ";
message += exception?.ToString() ?? "<null exception>";
Log(LogType.Exception, message);
}
public void Dispose()
{
// Flushes and closes the StreamWriter and the underlying stream
streamWriter.Close();
disposed = true;
}
}
}