Fra*_*hop 8 c# logging elasticsearch asp.net-core-webapi
我有一个用C#和Elasticsearch编写的 .NET Web API 。在 Elasticsearch 上,我有一个索引“ logging ”,我想将我的日志从 API 推送到其中。
我不知道如何将我的日志从 C# API 获取到弹性“日志记录”中。我阅读了诸如Logging with ElasticSearch... 之类的文档,但我的 Elasticsearch 中没有可用的 logstash。所以我正在寻找一个包,它可以帮助我以简单的方式登录。我认为需要交出索引“记录”的,所以它知道在哪里登录。
有人可以为此推荐文档和/或包吗?
还是我需要自己编程?
Elasticsearch“只是”一个日志浏览器。为了浏览您的日志,您必须生成这些日志。
例如,将您的应用程序配置为使用 Serilog ( https://stackify.com/serilog-tutorial-net-logging/ )。它将生成日志文件。
然后,将接收器配置为 Elasticsearch ( https://github.com/serilog/serilog-sinks-elasticsearch )。它会将您的日志写入到 elasticsearch 可以读取的位置。
感谢 Skrface 的支持。我将为其他遇到相同问题的人总结我的代码。(对于 CLI 和解决方案文件夹,请看下面。)
在 .NET Core Web API 中实现
添加 NuGet 包:
添加到 appsettings.json:
"Serilog": {
"MinimumLevel": "Information",
"WriteTo": [
{
"Name": "RollingFile",
"Args": {
"pathFormat": "C:\\Temp\\log-{Date}.txt",
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] {Message}{NewLine}{Exception}"
}
}
],
"Properties": {
"Application": "DataPicker.Api"
}
Run Code Online (Sandbox Code Playgroud)
}
修改 Startup.cs
Run Code Online (Sandbox Code Playgroud)public IConfiguration Configuration { get; } public Startup(IHostingEnvironment hostingEnvironment) { var builder = new ConfigurationBuilder() .SetBasePath(hostingEnvironment.ContentRootPath) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile($"appsettings.{hostingEnvironment.EnvironmentName}.json", reloadOnChange: true, optional: true) .AddEnvironmentVariables(); Configuration = builder.Build(); var uri = Configuration["ConnectionStrings:ElasticSearchConnection"]; Log.Logger = new LoggerConfiguration() .Enrich.FromLogContext() .WriteTo.Elasticsearch(new ElasticsearchSinkOptions(new Uri(uri)) { AutoRegisterTemplate = true, }) .CreateLogger(); }
添加到 Startup.cs Configure(..)
loggerFactory.AddSerilog();
修改控制器:
public class MyController : Controller
{
private readonly ILogger<MyController > logger;
public MyController (ILogger<MyController> logger)
{
this.logger = logger;
}
Run Code Online (Sandbox Code Playgroud)
并使用 POST / PUT / GET / ... -method 中的日志记录:
logger.LogDebug("My message");
logger.LogError("Exception: " + ex.Message);
Run Code Online (Sandbox Code Playgroud)
在 .NET Core CLI 中实现
添加 NuGet 包:
将 Programm.cs 添加到 Main(..)
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.MinimumLevel.Override("Microsoft", LogEventLevel.Information)
.Enrich.FromLogContext()
.WriteTo.Elasticsearch(new ElasticsearchSinkOptions(new Uri("myUri:myPort")) // e.g. "http://localhost:9200"
{
AutoRegisterTemplate = true,
})
.CreateLogger();
Run Code Online (Sandbox Code Playgroud)
而不是这样使用它:
Log.Debug("Start CLI !");
Log.Error("Can't create data base entry: " + ex.Message);
Run Code Online (Sandbox Code Playgroud)
在 .NET Core 解决方案文件夹中实现
就像在 CLI 中一样工作(见上文),只需使用您的构造函数而不是 Main(..)。
| 归档时间: |
|
| 查看次数: |
15534 次 |
| 最近记录: |