|
| 1 | +using Azure.Data.Tables; |
| 2 | + |
| 3 | +using Microsoft.Extensions.Logging; |
| 4 | + |
| 5 | +using TableStorage.Abstracts.Extensions; |
| 6 | +using TableStorage.Abstracts.Tests.Models; |
| 7 | + |
| 8 | +namespace TableStorage.Abstracts.Tests.Services; |
| 9 | + |
| 10 | +public class LogEventRepository : TableRepository<LogEvent>, ILogEventRepository |
| 11 | +{ |
| 12 | + public LogEventRepository(ILoggerFactory logFactory, TableServiceClient tableServiceClient) |
| 13 | + : base(logFactory, tableServiceClient) |
| 14 | + { |
| 15 | + } |
| 16 | + |
| 17 | + public async Task<PagedResult<LogEvent>> QueryByDate( |
| 18 | + DateOnly date, |
| 19 | + string? level = null, |
| 20 | + string? continuationToken = null, |
| 21 | + int? pageSize = 100, |
| 22 | + CancellationToken cancellationToken = default) |
| 23 | + { |
| 24 | + var baseDate = date.ToDateTime(TimeOnly.MinValue, DateTimeKind.Utc); |
| 25 | + |
| 26 | + var upperDate = baseDate.ToReverseChronological(); |
| 27 | + var lowwerDate = baseDate.AddDays(1).ToReverseChronological(); |
| 28 | + |
| 29 | + var upper = $"{upperDate.Ticks:D19}"; |
| 30 | + var lower = $"{lowwerDate.Ticks:D19}"; |
| 31 | + |
| 32 | + var filter = $"(PartitionKey ge '{lower}') and (PartitionKey lt '{upper}')"; |
| 33 | + |
| 34 | + if (level.HasValue()) |
| 35 | + filter += $" and (Level eq '{level}')"; |
| 36 | + |
| 37 | + return await FindPageAsync(filter, continuationToken, pageSize, cancellationToken); |
| 38 | + } |
| 39 | + |
| 40 | + public override string NewRowKey() |
| 41 | + { |
| 42 | + // store newest log first |
| 43 | + var timestamp = DateTimeOffset.UtcNow.ToReverseChronological(); |
| 44 | + return Ulid.NewUlid(timestamp).ToString(); |
| 45 | + } |
| 46 | + |
| 47 | + protected override void BeforeSave(LogEvent entity) |
| 48 | + { |
| 49 | + if (entity.RowKey.IsNullOrWhiteSpace()) |
| 50 | + entity.RowKey = NewRowKey(); |
| 51 | + |
| 52 | + if (entity.PartitionKey.IsNullOrWhiteSpace()) |
| 53 | + { |
| 54 | + var timespan = entity.Timestamp ?? DateTimeOffset.UtcNow; |
| 55 | + var roundedDate = timespan |
| 56 | + .Round(TimeSpan.FromMinutes(5)) |
| 57 | + .ToReverseChronological(); |
| 58 | + |
| 59 | + // create a 19 character String for reverse chronological ordering. |
| 60 | + entity.PartitionKey = $"{roundedDate.Ticks:D19}"; |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + protected override string GetTableName() => "LogEvent"; |
| 65 | +} |
0 commit comments