summaryrefslogtreecommitdiff
path: root/NW4RTools/Logger.cs
blob: 9f7d063ec3ab9101b2f10150ff83797d7850d727 (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
using System;
using System.Collections.Generic;
using System.Text;

namespace NW4RTools {
	public class LogContext : IDisposable {
		// An awful, awful hack
		private readonly ILogger Owner;

		public LogContext(ILogger owner) {
			Owner = owner;
		}

		void IDisposable.Dispose() {
			Owner.Pop();
		}
	}

	public interface ILogger {
		void Send(string format, params object[] args);
		LogContext Push(string format, params object[] args);
		void Pop();
		void Block();
		void Unblock();
	}

	public class NullLogger : ILogger {
		public NullLogger() { }

		public void Send(string format, params object[] args) {
		}

		public LogContext Push(string format, params object[] args) {
			return new LogContext(this);
		}

		public void Pop() {
		}

		public void Block() {
		}

		public void Unblock() {
		}
	}

	public class ConsoleLogger : ILogger {
		private List<string> PrefixElements;
		private List<string> Names;
		private int BlockCount;
		private string Prefix;

		public ConsoleLogger() {
			Names = new List<string>();
			Names.Add("root");

			PrefixElements = new List<string>();
			PrefixElements.Add("|");

			RebuildPrefix();
		}

		private void RebuildPrefix() {
			Prefix = string.Join("  ", PrefixElements.ToArray()) + "- ";
		}

		public void Send(string format, params object[] args) {
			if (BlockCount > 0)
				return;

			Console.Write(Prefix);
			Console.WriteLine(format, args);
		}

		public LogContext Push(string format, params object[] args) {
			string n = string.Format(format, args);
			Console.Write(Prefix);
			Console.Write("=== ");
			Console.WriteLine(n);

			Names.Add(n);

			PrefixElements.Add("-");
			RebuildPrefix();

			return new LogContext(this);
		}

		public void Pop() {
			PrefixElements.RemoveAt(PrefixElements.Count - 1);
			RebuildPrefix();

			string n = Names[Names.Count - 1];
			Names.RemoveAt(Names.Count - 1);
			Console.Write(Prefix);
			Console.Write("=/= end ");
			Console.WriteLine(n);
		}

		public void Block() {
			BlockCount += 1;
		}

		public void Unblock() {
			BlockCount -= 1;
		}
	}
}