Skip to content

Commit

Permalink
Quickstart configuration (#20)
Browse files Browse the repository at this point in the history
Quickstart configuration
  • Loading branch information
Bardin08 authored Feb 16, 2024
2 parents 4c6d330 + 10ab26b commit a5d2554
Show file tree
Hide file tree
Showing 15 changed files with 148 additions and 20 deletions.
7 changes: 7 additions & 0 deletions X.Serilog.Sinks.Telegram.sln
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "examples", "examples", "{4A
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WebApp", "examples\WebApp\WebApp.csproj", "{15736D36-94A1-4E3F-8A5F-EFEFE27F1995}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ConsoleApp", "examples\ConsoleApp\ConsoleApp.csproj", "{D007F793-195D-448A-A34E-74EF0245F9D3}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand All @@ -22,9 +24,14 @@ Global
{15736D36-94A1-4E3F-8A5F-EFEFE27F1995}.Debug|Any CPU.Build.0 = Debug|Any CPU
{15736D36-94A1-4E3F-8A5F-EFEFE27F1995}.Release|Any CPU.ActiveCfg = Release|Any CPU
{15736D36-94A1-4E3F-8A5F-EFEFE27F1995}.Release|Any CPU.Build.0 = Release|Any CPU
{D007F793-195D-448A-A34E-74EF0245F9D3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D007F793-195D-448A-A34E-74EF0245F9D3}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D007F793-195D-448A-A34E-74EF0245F9D3}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D007F793-195D-448A-A34E-74EF0245F9D3}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{807F309C-4CE3-4E68-8D46-9044A0A7BD6A} = {652C6F31-3E8C-400E-9716-ACF591E48E6F}
{15736D36-94A1-4E3F-8A5F-EFEFE27F1995} = {4A2DA76C-10DE-476D-A26E-16FAB3CBFC8C}
{D007F793-195D-448A-A34E-74EF0245F9D3} = {4A2DA76C-10DE-476D-A26E-16FAB3CBFC8C}
EndGlobalSection
EndGlobal
19 changes: 19 additions & 0 deletions examples/ConsoleApp/ConsoleApp.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.Sinks.Console" Version="5.0.1" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\..\src\X.Serilog.Sinks.Telegram\X.Serilog.Sinks.Telegram.csproj" />
</ItemGroup>

</Project>
22 changes: 22 additions & 0 deletions examples/ConsoleApp/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
using Serilog;
using Serilog.Events;
using X.Serilog.Sinks.Telegram.Extensions;

const string botToken = "TELEGRAM_BOT_TOKEN";
const string loggingChatId = "CHANNEL_OR_CHAT_ID";

Log.Logger = new LoggerConfiguration()
.WriteTo.TelegramCore(
token: botToken,
chatId: loggingChatId,
logLevel: LogEventLevel.Verbose)
.WriteTo.Console()
.CreateLogger();


while (true)
{
var level = Random.Shared.NextInt64(0, 6);
Log.Logger.Write((LogEventLevel)level, "Message");
await Task.Delay(500);
}
1 change: 1 addition & 0 deletions examples/WebApp/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
using X.Serilog.Sinks.Telegram;
using X.Serilog.Sinks.Telegram.Batch.Rules;
using X.Serilog.Sinks.Telegram.Configuration;
using X.Serilog.Sinks.Telegram.Extensions;
using X.Serilog.Sinks.Telegram.Filters;

var builder = WebApplication.CreateBuilder(args);
Expand Down
5 changes: 3 additions & 2 deletions examples/WebApp/WebApp.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,9 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Serilog.AspNetCore" Version="7.0.0"/>
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
<PackageReference Include="Serilog.AspNetCore" Version="8.0.1" />
<PackageReference Include="Serilog.Sinks.Console" Version="5.0.1" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" />
</ItemGroup>


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,15 +40,7 @@ public TimeSpan RuleCheckPeriod
/// </summary>
public IImmutableList<IExecutionHook> BatchProcessingExecutionHooks
=> BatchProcessingRules
.Select(rule =>
{
if (rule is IExecutionHook hook)
{
return hook;
}
return null;
})
.Where(hook => hook != null)
.ToImmutableList()!;
.Where(rule => rule is IExecutionHook)
.Cast<IExecutionHook>()
.ToImmutableList();
}
26 changes: 26 additions & 0 deletions src/X.Serilog.Sinks.Telegram/Configuration/TelegramSinkDefaults.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,32 @@ namespace X.Serilog.Sinks.Telegram.Configuration;
/// </summary>
public static class TelegramSinkDefaults
{
/// <summary>
/// Gets the logging mode for the application.
/// </summary>
/// <value>
/// The logging mode determines how log messages are processed and formatted before being sent.
/// In this case, it is set to return <see cref="LoggingMode.Logs"/>, which indicates that log messages
/// will be published individually to the specified Telegram channel.
/// </value>
/// <remarks>
/// This property is read-only and returns the default logging mode of the system.
/// It is crucial for configuring the overall logging strategy of the application.
/// For example, when set to <see cref="LoggingMode.Logs"/>, each log message is sent as it occurs.
/// Other modes, like <see cref="LoggingMode.AggregatedNotifications"/>, could aggregate messages over a period
/// or until a certain condition is met before sending.
/// </remarks>
public static LoggingMode DefaultFormatterMode => LoggingMode.AggregatedNotifications;

public static FormatterConfiguration DefaultFormatterConfiguration => new()
{
UseEmoji = true,
ReadableApplicationName = "X.Serilog.Telegram.Sink",
IncludeException = false,
IncludeProperties = false,
TimeZone = TimeZoneInfo.Utc
};

/// <summary>
/// The limit on the number of log events to be included in a single batch.
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
using System.Collections.Immutable;
using X.Serilog.Sinks.Telegram.Batch.Rules;
using X.Serilog.Sinks.Telegram.Configuration;
using X.Serilog.Sinks.Telegram.Filters;

namespace X.Serilog.Sinks.Telegram.Extensions;

public static class DependencyInjectionExtensions
{
public static LoggerConfiguration TelegramCore(
this LoggerSinkConfiguration sinkConfig,
string token,
string chatId,
LogEventLevel logLevel
)
{
ArgumentNullException.ThrowIfNull(sinkConfig);
ArgumentNullException.ThrowIfNull(token);
ArgumentNullException.ThrowIfNull(chatId);

return TelegramCoreInternal(sinkConfig, token, chatId, logLevel);
}

private static LoggerConfiguration TelegramCoreInternal(
LoggerSinkConfiguration sinkConfig,
string token,
string chatId,
LogEventLevel logLevel)
{
return sinkConfig.Telegram(config =>
{
config.Token = token;
config.ChatId = chatId;
config.Mode = TelegramSinkDefaults.DefaultFormatterMode;
config.BatchPostingLimit = TelegramSinkDefaults.BatchPostingLimit;
config.BatchEmittingRulesConfiguration = new BatchEmittingRulesConfiguration
{
RuleCheckPeriod = TelegramSinkDefaults.RulesCheckPeriod,
BatchProcessingRules = new List<IRule>
{
new BatchSizeRule(config.LogsAccessor, batchSize: config.BatchPostingLimit),
// send logs to the Telegram once per 250 seconds
new OncePerTimeRule(TelegramSinkDefaults.RulesCheckPeriod * 50)
}.ToImmutableList()
};
config.FormatterConfiguration = TelegramSinkDefaults.DefaultFormatterConfiguration;
config.LogFiltersConfiguration = new LogsFiltersConfiguration()
{
ApplyLogFilters = false,
Filters = new ImmutableArray<IFilter>()
};
},
messageFormatter: null!,
restrictedToMinimumLevel: logLevel);
}
}
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
using System.Threading.Channels;
using X.Serilog.Sinks.Telegram.Batch;
using X.Serilog.Sinks.Telegram.Configuration;
using X.Serilog.Sinks.Telegram.Formatters;

namespace X.Serilog.Sinks.Telegram.Configuration;
namespace X.Serilog.Sinks.Telegram.Extensions;

public static class LoggerConfigurationTelegramExtensions
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ public class DefaultAggregatedNotificationsFormatter : MessageFormatterBase
public override List<string> Format(
ICollection<LogEntry> logEntries,
FormatterConfiguration config,
Func<ICollection<LogEntry>, FormatterConfiguration, List<string>> formatter = null)
Func<ICollection<LogEntry>, FormatterConfiguration, List<string>>? formatter = null)
{
formatter ??= DefaultFormatter;
return base.Format(logEntries, config, formatter);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ internal class DefaultLogFormatter : MessageFormatterBase
/// <exception cref="ArgumentException">Throws when, after using the formatter, the message is null, empty, or whitespace.</exception>
public override List<string> Format(ICollection<LogEntry> logEntries,
FormatterConfiguration config,
Func<ICollection<LogEntry>, FormatterConfiguration, List<string>> formatter = null)
Func<ICollection<LogEntry>, FormatterConfiguration, List<string>>? formatter = null)
{
if (!NotEmpty(logEntries))
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,5 +13,5 @@ public interface IMessageFormatter
/// <returns>Human-readable message.</returns>
List<string> Format(ICollection<LogEntry> logEntries,
FormatterConfiguration config,
Func<ICollection<LogEntry>, FormatterConfiguration, List<string>> formatter = null);
Func<ICollection<LogEntry>, FormatterConfiguration, List<string>>? formatter = null);
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ public abstract class MessageFormatterBase : IMessageFormatter
/// <inheritdoc />
public virtual List<string> Format(ICollection<LogEntry> logEntries,
FormatterConfiguration config,
Func<ICollection<LogEntry>, FormatterConfiguration, List<string>> formatter = null)
Func<ICollection<LogEntry>, FormatterConfiguration, List<string>>? formatter = null)
{
if (!NotEmpty(logEntries))
{
Expand Down
3 changes: 2 additions & 1 deletion src/X.Serilog.Sinks.Telegram/TelegramSink.cs
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,8 @@ private async Task EmitBatchInternalAsync(int batchSize, CancellationToken cance
private async Task<IImmutableList<string>> GetMessagesFromQueueAsync(int amount)
{
var logsBatch = await _logsQueueAccessor.DequeueSeveralAsync(amount);
var events = logsBatch.Where(log => log is not null)
var events = logsBatch
.Where(log => log is not null)
.Select(LogEntry.MapFrom)
.ToList();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Serilog" Version="3.0.1"/>
<PackageReference Include="Serilog" Version="3.1.1" />
<PackageReference Include="Telegram.Bot" Version="19.0.0"/>
</ItemGroup>

Expand Down

0 comments on commit a5d2554

Please sign in to comment.