Add NLog
This commit is contained in:
parent
f461be1dbe
commit
08c6373012
@ -1,6 +1,7 @@
|
||||
using System.Collections.Concurrent;
|
||||
using Discord.Audio;
|
||||
using NAudio.Wave;
|
||||
using NLog;
|
||||
|
||||
namespace Elementary.Audio;
|
||||
|
||||
@ -30,12 +31,15 @@ public class PlaybackQueue
|
||||
|
||||
private bool _isPlaying;
|
||||
|
||||
private ILogger _logger;
|
||||
|
||||
public PlaybackQueue(AudioManager audioManager)
|
||||
{
|
||||
_queue = new();
|
||||
_isPlaying = false;
|
||||
_lock = new();
|
||||
_audioManager = audioManager;
|
||||
_logger = LogManager.GetCurrentClassLogger();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@ -45,14 +49,14 @@ public class PlaybackQueue
|
||||
public async Task Enqueue(PlaybackJob job)
|
||||
{
|
||||
_queue.Enqueue(job);
|
||||
Console.WriteLine("Enqueued");
|
||||
_logger.Info("Enqueued");
|
||||
if (!_isPlaying)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
if (!_isPlaying)
|
||||
{
|
||||
Console.WriteLine("Start Playing due to empty queue");
|
||||
_logger.Info("Start Playing due to empty queue");
|
||||
PlayNext();
|
||||
}
|
||||
}
|
||||
@ -64,14 +68,14 @@ public class PlaybackQueue
|
||||
public void Flush()
|
||||
{
|
||||
_queue.Clear();
|
||||
Console.WriteLine("Queue Flushed");
|
||||
_logger.Info("Queue Flushed");
|
||||
}
|
||||
|
||||
private async void PlayNext()
|
||||
{
|
||||
if (_queue.TryDequeue(out var currentStream))
|
||||
{
|
||||
Console.WriteLine("Start Playing");
|
||||
_logger.Info("Start Playing");
|
||||
|
||||
_isPlaying = true;
|
||||
await (currentStream.Type switch
|
||||
@ -80,14 +84,14 @@ public class PlaybackQueue
|
||||
JobType.Text => _audioManager.PlayText(currentStream.Text),
|
||||
_ => throw new ArgumentOutOfRangeException()
|
||||
});
|
||||
Console.WriteLine("Finished Playing");
|
||||
_logger.Info("Finished Playing");
|
||||
await Task.Delay(200);
|
||||
_isPlaying = false;
|
||||
PlayNext();
|
||||
}
|
||||
else if (_queue.IsEmpty)
|
||||
{
|
||||
Console.WriteLine("Queue is empty");
|
||||
_logger.Info("Queue is empty");
|
||||
_isPlaying = false;
|
||||
}
|
||||
}
|
||||
|
@ -1,10 +1,13 @@
|
||||
using System.Text.Json;
|
||||
using NLog;
|
||||
|
||||
namespace Elementary.Audio;
|
||||
|
||||
public class SozaiAPI
|
||||
{
|
||||
private Uri AssetsInfoUrl = new("https://synchthia-sounds.storage.googleapis.com/index.json");
|
||||
private ILogger _logger;
|
||||
|
||||
private Uri AssetsInfoUrl = new("https://r2.sim1222.com/sozai/index.json");
|
||||
private Asset[] Assets;
|
||||
|
||||
private class Asset
|
||||
@ -26,6 +29,7 @@ public class SozaiAPI
|
||||
public SozaiAPI()
|
||||
{
|
||||
_client = new HttpClient();
|
||||
_logger = LogManager.GetCurrentClassLogger();
|
||||
}
|
||||
|
||||
public async Task Setup()
|
||||
@ -34,7 +38,8 @@ public class SozaiAPI
|
||||
var stream = await response.Content.ReadAsStreamAsync();
|
||||
Assets = await JsonSerializer.DeserializeAsync<Asset[]>(stream);
|
||||
|
||||
Console.WriteLine($"Loaded {Assets.Length} assets");
|
||||
// Console.WriteLine($"Loaded {Assets.Length} assets");
|
||||
_logger.Info($"Loaded {Assets.Length} assets");
|
||||
}
|
||||
|
||||
public async Task<Stream?> GetAudioStream(string name)
|
||||
|
@ -1,5 +1,6 @@
|
||||
using System.Net.Http.Json;
|
||||
using System.Text;
|
||||
using NLog;
|
||||
|
||||
namespace Elementary.Audio;
|
||||
|
||||
@ -7,6 +8,7 @@ public class VoicevoxAPI
|
||||
{
|
||||
private UriBuilder _APIRootUrl;
|
||||
private HttpClient _client;
|
||||
private ILogger _logger;
|
||||
|
||||
public async Task Setup(string url)
|
||||
{
|
||||
@ -14,6 +16,7 @@ public class VoicevoxAPI
|
||||
|
||||
_APIRootUrl = new UriBuilder($"{_url.Scheme}://{_url.Host}:{_url.Port}");
|
||||
_client = new HttpClient();
|
||||
_logger = LogManager.GetCurrentClassLogger();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@ -24,7 +27,7 @@ public class VoicevoxAPI
|
||||
/// <returns></returns>
|
||||
public async Task<Stream?> Speak(string text, string speaker = "47")
|
||||
{
|
||||
Console.WriteLine($"Requested TTS {text}");
|
||||
_logger.Info($"Requested TTS {text}");
|
||||
|
||||
var query = await GetAudioQuery(text, speaker);
|
||||
if (query == null) return null;
|
||||
|
@ -3,6 +3,7 @@ using Discord.Audio;
|
||||
using Discord.Commands;
|
||||
using Discord.WebSocket;
|
||||
using Elementary.Audio;
|
||||
using NLog;
|
||||
|
||||
namespace Elementary.Commands;
|
||||
|
||||
@ -13,6 +14,7 @@ public class Handler
|
||||
private readonly IServiceProvider _services;
|
||||
private readonly AudioManager _audioManager;
|
||||
private readonly MessageHandler _messageHandler;
|
||||
private ILogger _logger;
|
||||
|
||||
// Retrieve client and CommandService instance via ctor
|
||||
public Handler(DiscordSocketClient client, CommandService commands, IServiceProvider services,
|
||||
@ -23,6 +25,7 @@ public class Handler
|
||||
_services = services;
|
||||
_audioManager = audioManager;
|
||||
_messageHandler = messageHandler;
|
||||
_logger = LogManager.GetCurrentClassLogger();
|
||||
}
|
||||
|
||||
public async Task Setup()
|
||||
@ -52,7 +55,7 @@ public class Handler
|
||||
|
||||
if (_audioManager.isConnected)
|
||||
{
|
||||
Console.WriteLine("Handling message");
|
||||
_logger.Info("Handling message");
|
||||
await _messageHandler.HandleMessage(message);
|
||||
}
|
||||
}
|
||||
|
@ -17,15 +17,16 @@ public class DiscordSettings
|
||||
public class Configuration
|
||||
{
|
||||
public AppSettings AppSettings { get; set; }
|
||||
public IConfigurationRoot ConfigurationRoot { get; set; }
|
||||
|
||||
public static Configuration LoadFromJson()
|
||||
public Configuration()
|
||||
{
|
||||
var builder = new ConfigurationBuilder()
|
||||
.AddJsonFile("appsettings.json", false, true);
|
||||
var configuration = builder.Build();
|
||||
.SetBasePath(Directory.GetCurrentDirectory())
|
||||
.AddJsonFile("appsettings.json", false, true)
|
||||
.Build();
|
||||
|
||||
var config = new Configuration();
|
||||
configuration.Bind(config);
|
||||
return config;
|
||||
builder.Bind(this);
|
||||
ConfigurationRoot = builder;
|
||||
}
|
||||
}
|
@ -28,6 +28,8 @@
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration.UserSecrets" Version="7.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0" />
|
||||
<PackageReference Include="NAudio" Version="2.1.0" />
|
||||
<PackageReference Include="NLog" Version="5.2.2" />
|
||||
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.2" />
|
||||
<PackageReference Include="System.Speech" Version="7.0.0" />
|
||||
</ItemGroup>
|
||||
|
||||
@ -47,6 +49,9 @@
|
||||
<None Update="bassmix.dll">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="nlog.config">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
@ -8,13 +8,19 @@ using Elementary.Audio;
|
||||
using Elementary.Commands;
|
||||
using ManagedBass;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using NAudio.Wave;
|
||||
using NLog;
|
||||
using NLog.Extensions.Logging;
|
||||
using Configuration = Elementary.Config.Configuration;
|
||||
using ILogger = NLog.ILogger;
|
||||
using LogLevel = NLog.LogLevel;
|
||||
|
||||
namespace Elementary;
|
||||
|
||||
public class Program
|
||||
{
|
||||
private ILogger _logger;
|
||||
private DiscordSocketClient _client;
|
||||
private IServiceProvider _services;
|
||||
private CommandService _commands;
|
||||
@ -29,13 +35,19 @@ public class Program
|
||||
|
||||
private async Task Setup()
|
||||
{
|
||||
var configuration = Configuration.LoadFromJson();
|
||||
var configuration = new Configuration();
|
||||
_client = new DiscordSocketClient(new DiscordSocketConfig
|
||||
{
|
||||
GatewayIntents = GatewayIntents.AllUnprivileged | GatewayIntents.MessageContent
|
||||
});
|
||||
_commands = new CommandService();
|
||||
_services = new ServiceCollection()
|
||||
.AddLogging(builder =>
|
||||
{
|
||||
builder.ClearProviders();
|
||||
builder.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
|
||||
builder.AddNLog(configuration.ConfigurationRoot);
|
||||
})
|
||||
.AddSingleton(_client)
|
||||
.AddSingleton(_commands)
|
||||
.AddSingleton<Handler>()
|
||||
@ -47,6 +59,8 @@ public class Program
|
||||
.AddSingleton<MessageHandler>()
|
||||
.BuildServiceProvider();
|
||||
|
||||
_logger = LogManager.GetCurrentClassLogger();
|
||||
|
||||
_sozaiAPI = _services.GetRequiredService<SozaiAPI>();
|
||||
_voicevoxAPI = _services.GetRequiredService<VoicevoxAPI>();
|
||||
|
||||
@ -68,9 +82,9 @@ public class Program
|
||||
await Task.Delay(-1); //keep the program running
|
||||
}
|
||||
|
||||
private static Task Log(LogMessage msg)
|
||||
private Task Log(LogMessage msg)
|
||||
{
|
||||
Console.WriteLine(msg.ToString());
|
||||
_logger.Log(LogLevel.FromString(msg.Severity.ToString()), msg.Exception, $"{msg.Source}: {msg.Message}");
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
30
Elementary/nlog.config
Normal file
30
Elementary/nlog.config
Normal file
@ -0,0 +1,30 @@
|
||||
<?xml version="1.0" encoding="utf-8" ?>
|
||||
<!-- XSD manual extracted from package NLog.Schema: https://www.nuget.org/packages/NLog.Schema-->
|
||||
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xsi:schemaLocation="NLog NLog.xsd"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
autoReload="true"
|
||||
internalLogFile="c:\temp\console-example-internal.log"
|
||||
internalLogLevel="Info" >
|
||||
|
||||
<!-- the targets to write to -->
|
||||
<targets>
|
||||
<!-- write logs to file -->
|
||||
<!-- <target xsi:type="File" name="logfile" fileName="c:\temp\console-example.log" -->
|
||||
<!-- layout="${longdate}|${level}|${message} |${all-event-properties} ${exception:format=tostring}" /> -->
|
||||
<!-- <target xsi:type="Console" name="logconsole" -->
|
||||
<!-- layout="${longdate} | ${level} |${message} |${all-event-properties} ${exception:format=tostring}" /> -->
|
||||
<target name="coloredConsole" xsi:type="ColoredConsole" useDefaultRowHighlightingRules="false"
|
||||
layout="${longdate} [${level:uppercase=true:padding=-4}] ${logger} | ${message} ${all-event-properties} ${exception:format=tostring}" >
|
||||
<highlight-row condition="level == LogLevel.Debug" foregroundColor="DarkGray" />
|
||||
<highlight-row condition="level == LogLevel.Info" foregroundColor="Gray" />
|
||||
<highlight-row condition="level == LogLevel.Warn" foregroundColor="Yellow" />
|
||||
<highlight-row condition="level == LogLevel.Error" foregroundColor="Red" />
|
||||
<highlight-row condition="level == LogLevel.Fatal" foregroundColor="Red" backgroundColor="White" />
|
||||
</target>
|
||||
</targets>
|
||||
|
||||
<!-- rules to map from logger name to target -->
|
||||
<rules>
|
||||
<logger name="*" minlevel="Trace" writeTo="logfile,coloredConsole" />
|
||||
</rules>
|
||||
</nlog>
|
Loading…
x
Reference in New Issue
Block a user