using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Driver;
namespace VanDerHeijden.Logging.MongoDb;
///
/// Represents a single log entry stored in MongoDB.
///
public class LogEntry
{
/// Gets or sets the MongoDB document identifier.
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; } = ObjectId.GenerateNewId().ToString();
/// Gets or sets the UTC timestamp when the log entry was created.
public DateTime Timestamp { get; set; }
/// Gets or sets the log level (e.g. "Information", "Error").
public string Level { get; set; } = string.Empty;
/// Gets or sets the logger category name.
public string Category { get; set; } = string.Empty;
/// Gets or sets the formatted log message.
public string Message { get; set; } = string.Empty;
/// Gets or sets the string representation of an associated exception, or if none.
public string? Exception { get; set; }
/// Gets or sets the request path (e.g. "/api/users"), or outside an HTTP context.
public string? Path { get; set; }
/// Gets or sets the HTTP method (e.g. "GET"), or outside an HTTP context.
public string? Method { get; set; }
/// Gets or sets the client IP address, or outside an HTTP context.
public string? ClientIp { get; set; }
/// Gets or sets the Referer header value, or outside an HTTP context.
public string? Referer { get; set; }
/// Gets or sets the User-Agent header value, or outside an HTTP context.
public string? UserAgent { get; set; }
}
///
/// Writes batches of documents to a MongoDB collection using InsertManyAsync.
///
/// The MongoDB collection that receives log entries.
public sealed class MongoDbLogWriter(IMongoCollection collection) : IBatchedLogWriter
{
///
/// Inserts all entries in the batch into the MongoDB collection.
///
/// The log entries to insert.
/// A token that can cancel the operation.
public async Task WriteBatchAsync(List entries, CancellationToken ct) =>
await collection.InsertManyAsync(entries, cancellationToken: ct);
///
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
}