c# - 如何为 Cloudwatch 创建自定义文本格式化程序?
问题描述
如前所述,我不明白如何为 Amazon Cloudwatch 创建自定义文本格式化程序:
var formatter = new MyCustomTextFormatter();
我正在尝试将 Serilog 日志写入 Amazon CloudWatch 而不是本地硬盘。为此,我正在关注此回购:
https://github.com/Cimpress-MCP/serilog-sinks-awscloudwatch
private readonly ITextFormatter textFormatter;
public ILoggerFactory ConfigureLogger()
{
LoggerFactory factory = new LoggerFactory();
var logGroupName = "myLoggrouName";
var region = Amazon.RegionEndpoint.EUWest1;
var client = new AmazonCloudWatchLogsClient(region);
//var formatter = new MyCustomTextFormatter();
var options = new CloudWatchSinkOptions()
{
LogGroupName = logGroupName,
//TextFormatter = formatter,
MinimumLogEventLevel = LogEventLevel.Information,
BatchSizeLimit = 100,
QueueSizeLimit = 10000,
Period = TimeSpan.FromSeconds(10),
CreateLogGroup = true,
LogStreamNameProvider = new DefaultLogStreamProvider(),
RetryAttempts = 5
};
Log.Logger = new LoggerConfiguration()
.WriteTo.AmazonCloudWatch(options, client)
.CreateLogger();
return factory;
}
能够将 Serilog 写入 Cloudwatch。
解决方案
我今天通过了同样的情况,我发现自定义格式化程序 - 默认情况下没有设置 - 它用于设置日志的写入方式,因此它将出现在 AWS 日志中。
您可以使用 Serilog 提供的界面开始创建简单的格式化程序,并根据您的情况进行调整。
public class AWSTextFormatter : ITextFormatter
{
public void Format(LogEvent logEvent, TextWriter output)
{
output.Write("Timestamp - {0} | Level - {1} | Message {2} {3}", logEvent.Timestamp, logEvent.Level, logEvent.MessageTemplate, output.NewLine);
if (logEvent.Exception != null)
{
output.Write("Exception - {0}", logEvent.Exception);
}
}
}
使用它
var customFormatter = new AWSTextFormatter();
var options = new CloudWatchSinkOptions
{
// the name of the CloudWatch Log group for logging
LogGroupName = logGroupName,
// the main formatter of the log event
TextFormatter = customFormatter,
// other defaults defaults
MinimumLogEventLevel = LogEventLevel.Information,
BatchSizeLimit = 100,
QueueSizeLimit = 10000,
Period = TimeSpan.FromSeconds(10),
CreateLogGroup = true,
LogStreamNameProvider = new DefaultLogStreamProvider(),
RetryAttempts = 5
};
在该方法中,您可以访问 LogEvent 并获取所需的所有信息。这一个类似于他们在 lib 中使用的,编写事件、异常和一些细节。
一个建议是在本地测试自定义格式化程序,将日志写入某个文件
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.WriteTo.RollingFile(customFormatter, Path.Combine(env.ContentRootPath, "Logs", "Log-{Date}.txt"))
.WriteTo.AmazonCloudWatch(options, client)
.CreateLogger();
日志显示的内容:
Timestamp - 1/9/2019 11:52:11 AM -02:00 | Level - Fatal | Message PROBLEM STARTING
APPLICATION
Exception - Couchbase.Configuration.Server.Serialization.BootstrapException: Could not
bootstrap - check inner exceptions for details.
推荐阅读
- javascript - Vue.JS 2.5.1:未捕获的语法错误:意外的令牌导出
- php - 我们如何将转换后的图像分辨率设置为与 imagemagick 中的源文件相同?
- javascript - 使用 JQuery Ajax 将 Javascript 数组传递给控制器
- c# - 在Unity C#中计算meshCollider是否需要为Convex或Concave?
- go - Gin-Gonic(golang)服务器上的 Axios POST 不工作
- java - 我的应用程序没有在手机或模拟器上运行
- node.js - 使用节点 JS 的 Spring Boot SSL
- php - 会话未传递给视图 laravel
- python - Django REST 框架:备用字段名称
- java - 如何在 SWT 表中显示 CCombo 组合框