Browse Source

Integrate TopShelf.NLog and increase debug logging

Nick Babcock 7 years ago
parent
commit
d8bf9857ef

+ 39 - 0
OhmGraphite/LoggerUtils.cs

@@ -0,0 +1,39 @@
+using System;
+using NLog;
+
+namespace OhmGraphite
+{
+    public static class LoggerUtils
+    {
+        public static void LogAction(this Logger logger, string msg, Action action)
+        {
+            try
+            {
+                logger.Debug("Starting: {0}", msg);
+                action();
+                logger.Debug("Finished: {0}", msg);
+            }
+            catch (Exception e)
+            {
+                logger.Error(e, "Exception: {0}", msg);
+                throw new Exception($"Exception with {msg}", e);
+            }
+        }
+
+        public static T LogFunction<T>(this Logger logger, string msg, Func<T> fn)
+        {
+            try
+            {
+                logger.Debug("Starting: {0}", msg);
+                var result = fn();
+                logger.Debug("Finished: {0}", msg);
+                return result;
+            }
+            catch (Exception e)
+            {
+                logger.Error(e, "Exception: {0}", msg);
+                throw new Exception($"Exception with {msg}", e);
+            }
+        }
+    }
+}

+ 52 - 0
OhmGraphite/MetricConfig.cs

@@ -0,0 +1,52 @@
+using System;
+using System.Configuration;
+using OpenHardwareMonitor.Hardware;
+
+namespace OhmGraphite
+{
+    public class MetricConfig
+    {
+        public string Host { get; }
+        public int Port { get; }
+        public Computer Computer { get; }
+        public TimeSpan Interval { get; }
+
+        public MetricConfig(string host, int port, Computer computer, TimeSpan interval)
+        {
+            Host = host;
+            Port = port;
+            Computer = computer;
+            Interval = interval;
+        }
+
+        public static MetricConfig ParseAppSettings()
+        {
+            string host = ConfigurationManager.AppSettings["host"] ?? "localhost";
+            if (!int.TryParse(ConfigurationManager.AppSettings["port"], out int port))
+            {
+                port = 2003;
+            }
+
+            if (!int.TryParse(ConfigurationManager.AppSettings["interval"], out int seconds))
+            {
+                seconds = 5;
+            }
+
+            var interval = TimeSpan.FromSeconds(seconds);
+
+            // We'll want to capture all available hardware metrics
+            // to send to graphite
+            var computer = new Computer
+            {
+                GPUEnabled = true,
+                MainboardEnabled = true,
+                CPUEnabled = true,
+                RAMEnabled = true,
+                FanControllerEnabled = true,
+                HDDEnabled = true
+            };
+
+            return new MetricConfig(host, port, computer, interval);
+        }
+    }
+}

+ 21 - 14
OhmGraphite/MetricTimer.cs

@@ -18,36 +18,43 @@ namespace OhmGraphite
         private readonly string _graphiteHost;
         private readonly Timer _timer;
 
-        public MetricTimer(Computer computer, TimeSpan interval, string graphiteHost, int graphitePort = 2003)
+        public MetricTimer(MetricConfig config)
         {
-            _computer = computer;
-            _graphitePort = graphitePort;
-            _graphiteHost = graphiteHost;
-            _timer = new Timer(interval.TotalMilliseconds) {AutoReset = true};
+            _computer = config.Computer;
+            _graphitePort = config.Port;
+            _graphiteHost = config.Host;
+            _timer = new Timer(config.Interval.TotalMilliseconds) {AutoReset = true};
             _timer.Elapsed += ReportMetrics;
         }
 
         public void Start()
         {
-            _computer.Open();
-            _timer.Start();
+            Logger.LogAction("starting metric timer", () =>
+            {
+                _computer.Open();
+                _timer.Start();
+            });
         }
 
         public void Stop()
         {
-            _computer.Close();
-            _timer.Stop();
+            Logger.LogAction("stopping metric timer", () =>
+            {
+                _computer.Close();
+                _timer.Stop();
+            });
         }
 
         private void ReportMetrics(object sender, ElapsedEventArgs e)
         {
-            // We don't want to transmit metrics across multiple seconds as they
-            // are being retrieved so calculate the timestamp of the signaled event
-            // only once.
-            long epoch = ((DateTimeOffset) e.SignalTime).ToUnixTimeSeconds();
-            string host = Environment.MachineName;
+            Logger.Debug("Starting to report metrics");
             try
             {
+                // We don't want to transmit metrics across multiple seconds as they
+                // are being retrieved so calculate the timestamp of the signaled event
+                // only once.
+                long epoch = new DateTimeOffset(e.SignalTime).ToUnixTimeSeconds();
+                string host = Environment.MachineName;
                 SendMetrics(host, epoch);
             }
             catch (Exception ex)

+ 1 - 0
OhmGraphite/OhmGraphite.csproj

@@ -32,6 +32,7 @@
   <ItemGroup>
     <PackageReference Include="NLog.Config" Version="4.4.12" />
     <PackageReference Include="TopShelf" Version="4.0.3" />
+    <PackageReference Include="Topshelf.NLog" Version="4.0.3" />
   </ItemGroup>
   <ItemGroup>
     <ProjectReference Include="..\LibreHardwareMonitor\OpenHardwareMonitorLib.csproj" />

+ 6 - 36
OhmGraphite/Program.cs

@@ -1,7 +1,4 @@
-using System;
-using OpenHardwareMonitor.Hardware;
-using System.Configuration;
-using NLog;
+using NLog;
 using Topshelf;
 
 namespace OhmGraphite
@@ -17,47 +14,20 @@ namespace OhmGraphite
                 {
                     // We need to know where the graphite server lives and how often
                     // to poll the hardware
-                    ParseConfig(out string host, out int port, out int seconds);
-
-                    // We'll want to capture all available hardware metrics
-                    // to send to graphite
-                    var computer = new Computer
-                    {
-                        GPUEnabled = true,
-                        MainboardEnabled = true,
-                        CPUEnabled = true,
-                        RAMEnabled = true,
-                        FanControllerEnabled = true,
-                        HDDEnabled = true
-                    };
-
-                    s.ConstructUsing(name => new MetricTimer(computer, TimeSpan.FromSeconds(seconds), host, port));
+                    var config = Logger.LogFunction("parse config", MetricConfig.ParseAppSettings);
+                    var seconds = config.Interval.TotalSeconds;
+                    Logger.Info($"Host: {config.Host} port: {config.Port} interval: {seconds}");
+                    s.ConstructUsing(name => Logger.LogFunction("creating timer", () => new MetricTimer(config)));
                     s.WhenStarted(tc => tc.Start());
                     s.WhenStopped(tc => tc.Stop());
                 });
+                x.UseNLog();
                 x.RunAsLocalSystem();
-
                 x.SetDescription("Extract hardware sensor data and exports it to a given host and port in a graphite compatible format");
                 x.SetDisplayName("Ohm Graphite");
                 x.SetServiceName("OhmGraphite");
                 x.OnException(ex => Logger.Error(ex, "OhmGraphite TopShelf encountered an error"));
             });
         }
-
-        private static void ParseConfig(out string host, out int port, out int seconds)
-        {
-            host = ConfigurationManager.AppSettings["host"] ?? "localhost";
-            if (!int.TryParse(ConfigurationManager.AppSettings["port"], out port))
-            {
-                port = 2003;
-            }
-
-            if (!int.TryParse(ConfigurationManager.AppSettings["interval"], out seconds))
-            {
-                seconds = 5;
-            }
-
-            Logger.Info($"Host: {host} port: {port} interval: {seconds}");
-        }
     }
 }