Guides for Serilog and EFCore (#2134)

* Add serilog guide

* added suggestions from Rozen

* Add efcore guide

* Fix review changes

* Fix grammatical errors & review points
This commit is contained in:
Duke
2022-03-02 20:08:51 +01:00
committed by GitHub
parent 7d8911bfed
commit 1fc07e742f
10 changed files with 213 additions and 1 deletions

View File

@@ -0,0 +1,61 @@
---
uid: Guides.OtherLibs.EFCore
title: EFCore
---
# Entity Framework Core
In this guide we will set up EFCore with a PostgreSQL database. Information on other databases will be at the bottom of this page.
## Prerequisites
- A simple bot with dependency injection configured
- A running PostgreSQL instance
- [EFCore CLI tools](https://docs.microsoft.com/en-us/ef/core/cli/dotnet#installing-the-tools)
## Downloading the required packages
You can install the following packages through your IDE or go to the nuget link to grab the dotnet cli command.
|Name|Link|
|--|--|
| `Microsoft.EntityFrameworkCore` | [link](https://www.nuget.org/packages/Microsoft.EntityFrameworkCore) |
| `Npgsql.EntityFrameworkCore.PostgreSQL` | [link](https://www.nuget.org/packages/Npgsql.EntityFrameworkCore.PostgreSQL)|
## Configuring the DbContext
To use EFCore, you need a DbContext to access everything in your database. The DbContext will look like this. Here is an example entity to show you how you can add more entities yourself later on.
[!code-csharp[DBContext Sample](samples/DbContextSample.cs)]
> [!NOTE]
> To learn more about creating the EFCore model, visit the following [link](https://docs.microsoft.com/en-us/ef/core/get-started/overview/first-app?tabs=netcore-cli#create-the-model)
## Adding the DbContext to your Dependency Injection container
To add your newly created DbContext to your Dependency Injection container, simply use the extension method provided by EFCore to add the context to your container. It should look something like this
[!code-csharp[DBContext Dependency Injection](samples/DbContextDepInjection.cs)]
> [!NOTE]
> You can find out how to get your connection string [here](https://www.connectionstrings.com/npgsql/standard/)
## Migrations
Before you can start using your DbContext, you have to migrate the changes you've made in your code to your actual database.
To learn more about migrations, visit the official Microsoft documentation [here](https://docs.microsoft.com/en-us/ef/core/managing-schemas/migrations/?tabs=dotnet-core-cli)
## Using the DbContext
You can now use the DbContext wherever you can inject it. Here's an example on injecting it into an interaction command module.
[!code-csharp[DBContext injected into interaction module](samples/InteractionModuleDISample.cs)]
## Using a different database provider
Here's a couple of popular database providers for EFCore and links to tutorials on how to set them up. The only thing that usually changes is the provider inside of your `DbContextOptions`
| Provider | Link |
|--|--|
| MySQL | [link](https://dev.mysql.com/doc/connector-net/en/connector-net-entityframework-core-example.html) |
| SQLite | [link](https://docs.microsoft.com/en-us/ef/core/get-started/overview/first-app?tabs=netcore-cli) |

Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

View File

@@ -0,0 +1,36 @@
using Discord;
using Serilog;
using Serilog.Events;
public class Program
{
static void Main(string[] args) => new Program().MainAsync().GetAwaiter().GetResult();
public async Task MainAsync()
{
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Verbose()
.Enrich.FromLogContext()
.WriteTo.Console()
.CreateLogger();
_client = new DiscordSocketClient();
_client.Log += LogAsync;
// You can assign your bot token to a string, and pass that in to connect.
// This is, however, insecure, particularly if you plan to have your code hosted in a public repository.
var token = "token";
// Some alternative options would be to keep your token in an Environment Variable or a standalone file.
// var token = Environment.GetEnvironmentVariable("NameOfYourEnvironmentVariable");
// var token = File.ReadAllText("token.txt");
// var token = JsonConvert.DeserializeObject<AConfigurationClass>(File.ReadAllText("config.json")).Token;
await _client.LoginAsync(TokenType.Bot, token);
await _client.StartAsync();
// Block this task until the program is closed.
await Task.Delay(Timeout.Infinite);
}
}

View File

@@ -0,0 +1,9 @@
private static ServiceProvider ConfigureServices()
{
return new ServiceCollection()
.AddDbContext<ApplicationDbContext>(
options => options.UseNpgsql("Your connection string")
)
[...]
.BuildServiceProvider();
}

View File

@@ -0,0 +1,19 @@
// ApplicationDbContext.cs
using Microsoft.EntityFrameworkCore;
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
{
}
public DbSet<UserEntity> Users { get; set; } = null!;
}
// UserEntity.cs
public class UserEntity
{
public ulong Id { get; set; }
public string Name { get; set; }
}

View File

@@ -0,0 +1,20 @@
using Discord;
public class SampleModule : InteractionModuleBase<SocketInteractionContext>
{
private readonly ApplicationDbContext _db;
public SampleModule(ApplicationDbContext db)
{
_db = db;
}
[SlashCommand("sample", "sample")]
public async Task Sample()
{
// Do stuff with your injected DbContext
var user = _db.Users.FirstOrDefault(x => x.Id == Context.User.Id);
...
}
}

View File

@@ -0,0 +1 @@
Log.Debug("Your log message, with {Variables}!", 10); // This will output "[21:51:00 DBG] Your log message, with 10!"

View File

@@ -0,0 +1,15 @@
private static async Task LogAsync(LogMessage message)
{
var severity = message.Severity switch
{
LogSeverity.Critical => LogEventLevel.Fatal,
LogSeverity.Error => LogEventLevel.Error,
LogSeverity.Warning => LogEventLevel.Warning,
LogSeverity.Info => LogEventLevel.Information,
LogSeverity.Verbose => LogEventLevel.Verbose,
LogSeverity.Debug => LogEventLevel.Debug,
_ => LogEventLevel.Information
};
Log.Write(severity, message.Exception, "[{Source}] {Message}", message.Source, message.Message);
await Task.CompletedTask;
}

View File

@@ -0,0 +1,45 @@
---
uid: Guides.OtherLibs.Serilog
title: Serilog
---
# Configuring serilog
## Prerequisites
- A basic working bot with a logging method as described in [Creating your first bot](xref:Guides.GettingStarted.FirstBot)
## Installing the Serilog package
You can install the following packages through your IDE or go to the nuget link to grab the dotnet cli command.
|Name|Link|
|--|--|
|`Serilog.Extensions.Logging`| [link](https://www.nuget.org/packages/Serilog.Extensions.Logging)|
|`Serilog.Sinks.Console`| [link](https://www.nuget.org/packages/Serilog.Sinks.Console)|
## Configuring Serilog
Serilog will be configured at the top of your async Main method, it looks like this
[!code-csharp[Configuring serilog](samples/ConfiguringSerilog.cs)]
## Modifying your logging method
For Serilog to log Discord events correctly, we have to map the Discord `LogSeverity` to the Serilog `LogEventLevel`. You can modify your log method to look like this.
[!code-csharp[Modifying your log method](samples/ModifyLogMethod.cs)]
## Testing
If you run your application now, you should see something similar to this
![Serilog output](images/serilog_output.png)
## Using your new logger in other places
Now that you have set up Serilog, you can use it everywhere in your application by simply calling
[!code-csharp[Log debug sample](samples/LogDebugSample.cs)]
> [!NOTE]
> Depending on your configured log level, the log messages may or may not show up in your console. Refer to [Serilog's github page](https://github.com/serilog/serilog/wiki/Configuration-Basics#minimum-level) for more information about log levels.

View File

@@ -95,7 +95,7 @@
topicUid: Guides.MessageComponents.TextInputs
- name: Advanced Concepts
topicUid: Guides.MessageComponents.Advanced
- name: Modal Basics
- name: Modal Basics
items:
- name: Introduction
topicUid: Guides.Modals.Intro
@@ -109,6 +109,12 @@
topicUid: Guides.GuildEvents.GettingUsers
- name: Modifying Events
topicUid: Guides.GuildEvents.Modifying
- name: Working with other libraries
items:
- name: Serilog
topicUid: Guides.OtherLibs.Serilog
- name: EFCore
topicUid: Guides.OtherLibs.EFCore
- name: Emoji
topicUid: Guides.Emoji
- name: Voice