Influx2Writer.cs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Threading.Tasks;
  5. using InfluxDB.Client;
  6. using InfluxDB.Client.Api.Domain;
  7. using InfluxDB.Client.Writes;
  8. using NLog;
  9. namespace OhmGraphite
  10. {
  11. public class Influx2Writer : IWriteMetrics
  12. {
  13. private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
  14. private readonly Influx2Config _config;
  15. private readonly string _localHost;
  16. public Influx2Writer(Influx2Config config, string localHost)
  17. {
  18. _config = config;
  19. _localHost = localHost;
  20. }
  21. public async Task ReportMetrics(DateTime reportTime, IEnumerable<ReportedValue> sensors)
  22. {
  23. var influxDbClient = new InfluxDBClient(_config.Options);
  24. var writeApi = influxDbClient.GetWriteApiAsync();
  25. var points = sensors.Select(x => NewPoint(reportTime, x)).ToList();
  26. await writeApi.WritePointsAsync(points);
  27. }
  28. private PointData NewPoint(DateTime reportTime, ReportedValue sensor)
  29. {
  30. var sensorType = Enum.GetName(typeof(SensorType), sensor.SensorType);
  31. return PointData.Measurement(sensorType)
  32. .Tag("host", _localHost)
  33. .Tag("app", "ohm")
  34. .Tag("hardware", sensor.Hardware)
  35. .Tag("hardware_type", Enum.GetName(typeof(HardwareType), sensor.HardwareType))
  36. .Tag("identifier", sensor.Identifier)
  37. .Tag("sensor", sensor.Sensor)
  38. .Field("value", sensor.Value)
  39. .Field("sensor_index", sensor.SensorIndex)
  40. .Timestamp(reportTime.ToUniversalTime(), WritePrecision.S);
  41. }
  42. public void Dispose()
  43. {
  44. }
  45. }
  46. }