summaryrefslogtreecommitdiff
path: root/src/SMAPI/Framework/Logging/ConsoleInterceptionManager.cs
blob: c04bcd1a84bb5b77ffde03602f6cecb69596a9fa (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
using System;

namespace StardewModdingAPI.Framework.Logging
{
    /// <summary>Manages console output interception.</summary>
    internal class ConsoleInterceptionManager : IDisposable
    {
        /*********
        ** Properties
        *********/
        /// <summary>The intercepting console writer.</summary>
        private readonly InterceptingTextWriter Output;


        /*********
        ** Accessors
        *********/
        /// <summary>The event raised when a message is written to the console directly.</summary>
        public event Action<string> OnMessageIntercepted;


        /*********
        ** Public methods
        *********/
        /// <summary>Construct an instance.</summary>
        public ConsoleInterceptionManager()
        {
            // redirect output through interceptor
            this.Output = new InterceptingTextWriter(Console.Out);
            this.Output.OnMessageIntercepted += line => this.OnMessageIntercepted?.Invoke(line);
            Console.SetOut(this.Output);
        }

        /// <summary>Get an exclusive lock and write to the console output without interception.</summary>
        /// <param name="action">The action to perform within the exclusive write block.</param>
        public void ExclusiveWriteWithoutInterception(Action action)
        {
            lock (Console.Out)
            {
                try
                {
                    this.Output.ShouldIntercept = false;
                    action();
                }
                finally
                {
                    this.Output.ShouldIntercept = true;
                }
            }
        }

        /// <summary>Release all resources.</summary>
        public void Dispose()
        {
            Console.SetOut(this.Output.Out);
            this.Output.Dispose();
        }
    }
}