Skip to content

Commit f6fab99

Browse files
authored
Merge pull request #7271 from umbraco/update/v16/logger-abstraction
Update logging with new abstraction/configuration
2 parents 1a218f1 + 49b9f83 commit f6fab99

File tree

4 files changed

+154
-72
lines changed

4 files changed

+154
-72
lines changed

16/umbraco-cms/fundamentals/backoffice/logviewer.md

Lines changed: 134 additions & 63 deletions
Original file line numberDiff line numberDiff line change
@@ -30,13 +30,13 @@ Here are some example queries to help you get started. For more details on the s
3030

3131
If you frequently use a custom query, you can save it for quick access. Type your query in the search box and click the heart icon to save it with a friendly name. Saved queries are stored in the `umbracoLogViewerQuery` table in the database.
3232

33-
## Implementing Your Own Log Viewer
33+
## Implementing Your Own Log Viewer Source
3434

35-
Umbraco allows you to implement a customn `ILogViewer` to fetch logs from alternative sources, such as **Azure Table Storage**.
35+
Umbraco allows you to implement a custom `ILogViewerRepository` and `ILogViewerService` to fetch logs from alternative sources, such as **Azure Table Storage**.
3636

37-
### Creating a Custom Log Viewer
37+
### Creating a Custom Log Viewer Repository
3838

39-
To fetch logs from Azure Table Storage, implement the `SerilogLogViewerSourceBase` class from `Umbraco.Cms.Core.Logging.Viewer`.
39+
To fetch logs from Azure Table Storage, extend the `LogViewerRepositoryBase` class from `Umbraco.Cms.Infrastructure.Services.Implement`.
4040

4141
{% hint style="info" %}
4242
This implementation requires the `Azure.Data.Tables` NuGet package.
@@ -47,114 +47,185 @@ using Azure;
4747
using Azure.Data.Tables;
4848
using Serilog.Events;
4949
using Serilog.Formatting.Compact.Reader;
50-
using Serilog.Sinks.AzureTableStorage;
50+
using Umbraco.Cms.Core.Composing;
5151
using Umbraco.Cms.Core.Logging.Viewer;
52-
using ITableEntity = Azure.Data.Tables.ITableEntity;
52+
using Umbraco.Cms.Core.Serialization;
53+
using Umbraco.Cms.Core.Services;
54+
using Umbraco.Cms.Infrastructure.Logging.Serilog;
55+
using Umbraco.Cms.Infrastructure.Services.Implement;
5356

5457
namespace My.Website;
5558

56-
public class AzureTableLogViewer : SerilogLogViewerSourceBase
59+
public class AzureTableLogsRepository : LogViewerRepositoryBase
5760
{
58-
public AzureTableLogViewer(ILogViewerConfig logViewerConfig, Serilog.ILogger serilogLog, ILogLevelLoader logLevelLoader)
59-
: base(logViewerConfig, logLevelLoader, serilogLog)
61+
private readonly IJsonSerializer _jsonSerializer;
62+
63+
public AzureTableLogsRepository(UmbracoFileConfiguration umbracoFileConfig, IJsonSerializer jsonSerializer) : base(
64+
umbracoFileConfig)
6065
{
66+
_jsonSerializer = jsonSerializer;
6167
}
6268

63-
public override bool CanHandleLargeLogs => true;
64-
65-
// This method will not be called - as we have indicated that this 'CanHandleLargeLogs'
66-
public override bool CheckCanOpenLogs(LogTimePeriod logTimePeriod) => throw new NotImplementedException();
67-
68-
protected override IReadOnlyList<LogEvent> GetLogs(LogTimePeriod logTimePeriod, ILogFilter filter, int skip, int take)
69+
protected override IEnumerable<ILogEntry> GetLogs(LogTimePeriod logTimePeriod, ILogFilter logFilter)
6970
{
70-
//Replace ACCOUNT_NAME and KEY with your actual Azure Storage Account details. The "Logs" parameter refers to the table name where logs will be stored and retrieved from.
71+
// This example uses a connection string compatible with the Azurite emulator
72+
// https://learn.microsoft.com/en-us/azure/storage/common/storage-use-azurite
7173
var client =
7274
new TableClient(
73-
"DefaultEndpointsProtocol=https;AccountName=ACCOUNT_NAME;AccountKey=KEY;EndpointSuffix=core.windows.net",
74-
"Logs");
75-
76-
// Table storage does not support skip, only take, so the best we can do is to not fetch more entities than we need in total.
77-
// See: https://learn.microsoft.com/en-us/rest/api/storageservices/writing-linq-queries-against-the-table-service#returning-the-top-n-entities for more info.
78-
var requiredEntities = skip + take;
79-
IEnumerable<AzureTableLogEntity> results = client.Query<AzureTableLogEntity>().Take(requiredEntities);
80-
81-
return results
82-
.Skip(skip)
83-
.Take(take)
84-
.Select(x => LogEventReader.ReadFromString(x.Data))
85-
// Filter by timestamp to avoid retrieving all logs from the table, preventing memory and performance issues
86-
.Where(evt => evt.Timestamp >= logTimePeriod.StartTime.Date &&
87-
evt.Timestamp <= logTimePeriod.EndTime.Date.AddDays(1).AddSeconds(-1))
88-
.Where(filter.TakeLogEvent)
89-
.ToList();
75+
"UseDevelopmentStorage=true",
76+
"LogEventEntity");
77+
78+
// Filter by timestamp to avoid retrieving all logs from the table, preventing memory and performance issues
79+
IEnumerable<AzureTableLogEntity> results = client.Query<AzureTableLogEntity>(
80+
entity => entity.Timestamp >= logTimePeriod.StartTime.Date &&
81+
entity.Timestamp <= logTimePeriod.EndTime.Date.AddDays(1).AddSeconds(-1));
82+
83+
// Read the data and apply logfilters
84+
IEnumerable<LogEvent> filteredData = results.Select(x => LogEventReader.ReadFromString(x.Data))
85+
.Where(logFilter.TakeLogEvent);
86+
87+
return filteredData.Select(x => new LogEntry
88+
{
89+
Timestamp = x.Timestamp,
90+
Level = Enum.Parse<Core.Logging.LogLevel>(x.Level.ToString()),
91+
MessageTemplateText = x.MessageTemplate.Text,
92+
Exception = x.Exception?.ToString(),
93+
Properties = MapLogMessageProperties(x.Properties),
94+
RenderedMessage = x.RenderMessage(),
95+
});
9096
}
9197

92-
public override IReadOnlyList<SavedLogSearch>? GetSavedSearches()
98+
private IReadOnlyDictionary<string, string?> MapLogMessageProperties(
99+
IReadOnlyDictionary<string, LogEventPropertyValue>? properties)
93100
{
94-
//This method is optional. If you store saved searches in Azure Table Storage, implement fetching logic here.
95-
return base.GetSavedSearches();
101+
var result = new Dictionary<string, string?>();
102+
103+
if (properties is not null)
104+
{
105+
foreach (KeyValuePair<string, LogEventPropertyValue> property in properties)
106+
{
107+
string? value;
108+
109+
if (property.Value is ScalarValue scalarValue)
110+
{
111+
value = scalarValue.Value?.ToString();
112+
}
113+
else if (property.Value is StructureValue structureValue)
114+
{
115+
var textWriter = new StringWriter();
116+
structureValue.Render(textWriter);
117+
value = textWriter.ToString();
118+
}
119+
else
120+
{
121+
value = _jsonSerializer.Serialize(property.Value);
122+
}
123+
124+
result.Add(property.Key, value);
125+
}
126+
}
127+
128+
return result;
96129
}
97130

98-
public override IReadOnlyList<SavedLogSearch>? AddSavedSearch(string? name, string? query)
131+
public class AzureTableLogEntity : ITableEntity
99132
{
100-
//This method is optional. If you store saved searches in Azure Table Storage, implement adding logic here.
101-
return base.AddSavedSearch(name, query);
102-
}
133+
public required string Data { get; set; }
103134

104-
public override IReadOnlyList<SavedLogSearch>? DeleteSavedSearch(string? name, string? query)
105-
{
106-
//This method is optional. If you store saved searches in Azure Table Storage, implement deleting logic here.
107-
return base.DeleteSavedSearch(name, query);
135+
public required string PartitionKey { get; set; }
136+
137+
public required string RowKey { get; set; }
138+
139+
public DateTimeOffset? Timestamp { get; set; }
140+
141+
public ETag ETag { get; set; }
108142
}
109143
}
144+
```
145+
146+
Azure Table Storage requires entities to implement the `ITableEntity` interface. Since Umbraco's default log entity does not implement this, a custom entity (`AzureTableLogEntity`) must be created to ensure logs are correctly fetched.
110147

111-
public class AzureTableLogEntity : LogEventEntity, ITableEntity
148+
### Creating a custom log viewer service
149+
150+
The next thing to do is create a new implementation of `ILogViewerService`. Amongst other things, this is responsible for figuring out whether a provided log query is allowed. Again a base class is available.
151+
152+
```csharp
153+
public class AzureTableLogsService : LogViewerServiceBase
112154
{
113-
public DateTimeOffset? Timestamp { get; set; }
155+
public AzureTableLogsService(
156+
ILogViewerQueryRepository logViewerQueryRepository,
157+
ICoreScopeProvider provider,
158+
ILogViewerRepository logViewerRepository)
159+
: base(logViewerQueryRepository, provider, logViewerRepository)
160+
{
161+
}
162+
163+
// Change this to what you think is sensible.
164+
// As an example, check whether more than 5 days off logs are requested.
165+
public override Task<Attempt<bool, LogViewerOperationStatus>> CanViewLogsAsync(LogTimePeriod logTimePeriod)
166+
{
167+
return logTimePeriod.EndTime - logTimePeriod.StartTime < TimeSpan.FromDays(5)
168+
? Task.FromResult(Attempt.SucceedWithStatus(LogViewerOperationStatus.Success, true))
169+
: Task.FromResult(Attempt.FailWithStatus(LogViewerOperationStatus.CancelledByLogsSizeValidation, false));
170+
}
171+
172+
public override ReadOnlyDictionary<string, LogLevel> GetLogLevelsFromSinks()
173+
{
174+
var configuredLogLevels = new Dictionary<string, LogLevel>
175+
{
176+
{ "Global", GetGlobalMinLogLevel() },
177+
{ "AzureTableStorage", LogViewerRepository.RestrictedToMinimumLevel() },
178+
};
114179

115-
public ETag ETag { get; set; }
180+
return configuredLogLevels.AsReadOnly();
181+
}
116182
}
117183
```
118184

119-
Azure Table Storage requires entities to implement the `ITableEntity` interface. Since Umbraco’s default log entity does not implement this, a custom entity (`AzureTableLogEntity`) must be created to ensure logs are correctly fetched and stored.
120-
121-
### Register implementation
185+
### Register implementations
122186

123-
Umbraco needs to be made aware that there is a new implementation of an `ILogViewer` to register. We also need to replace the default JSON LogViewer that we ship in the core of Umbraco.
187+
Umbraco needs to be made aware that there is a new implementation of an `ILogViewerRepository` and an `ILogViewerService`. These need to replace the default ones that are shipped with Umbraco.
124188

125189
```csharp
126190
using Umbraco.Cms.Core.Composing;
127191
using Umbraco.Cms.Infrastructure.DependencyInjection;
192+
using Umbraco.Cms.Core.Services;
128193

129194
namespace My.Website;
130195

131-
public class LogViewerSavedSearches : IComposer
132-
{
133-
public void Compose(IUmbracoBuilder builder) => builder.SetLogViewer<AzureTableLogViewer>();
196+
public class AzureTableLogsComposer : IComposer
197+
{
198+
public void Compose(IUmbracoBuilder builder)
199+
{
200+
builder.Services.AddUnique<ILogViewerRepository, AzureTableLogsRepository>();
201+
builder.Services.AddUnique<ILogViewerService, AzureTableLogsService>();
202+
}
203+
}
134204
}
135205
```
136206

137207
### Configuring Logging to Azure Table Storage
138208

139-
With the above two classes, the setup is in place to view logs from an Azure Table. However, logs are not yet persisted into the Azure Table Storage account. To enable persistence, configure the Serilog logging pipeline to store logs in Azure Table Storage.
209+
With the above three classes, the setup is in place to view logs from an Azure Table. However, logs are not yet persisted into the Azure Table Storage account. To enable persistence, configure the Serilog logging pipeline to store logs in Azure Table Storage.
140210

141-
* Install `Serilog.Sinks.AzureTableStorage` from NuGet.
142-
* Add a new sink to `appsettings.json` with credentials to persist logs to Azure.
211+
- Install `Serilog.Sinks.AzureTableStorage` from NuGet.
212+
- Add a new sink to `appsettings.json` with credentials to persist logs to Azure.
143213

144214
The following sink needs to be added to the [`Serilog:WriteTo`](https://github.com/serilog/serilog-sinks-azuretablestorage#json-configuration) array.
145215

146216
```json
147217
{
148-
"Name": "AzureTableStorage",
149-
"Args": {
150-
"storageTableName": "LogEventEntity",
151-
"formatter": "Serilog.Formatting.Compact.CompactJsonFormatter, Serilog.Formatting.Compact",
152-
"connectionString": "DefaultEndpointsProtocol=https;AccountName=ACCOUNT_NAME;AccountKey=KEY;EndpointSuffix=core.windows.net"}
218+
"Name": "AzureTableStorage",
219+
"Args": {
220+
"storageTableName": "LogEventEntity",
221+
"formatter": "Serilog.Formatting.Compact.CompactJsonFormatter, Serilog.Formatting.Compact",
222+
"connectionString": "DefaultEndpointsProtocol=https;AccountName=ACCOUNT_NAME;AccountKey=KEY;EndpointSuffix=core.windows.net"
223+
}
153224
}
154225
```
155226

156227
For more in-depth information about logging and how to configure it, see the [Logging](../code/debugging/logging.md) article.
157228

158229
### Compact Log Viewer - Desktop App
159230

160-
[Compact Log Viewer](https://www.microsoft.com/store/apps/9N8RV8LKTXRJ?cid=storebadge\&ocid=badge). A desktop tool is available for viewing and querying JSON log files in the same way as the built-in Log Viewer in Umbraco.
231+
[Compact Log Viewer](https://www.microsoft.com/store/apps/9N8RV8LKTXRJ?cid=storebadge&ocid=badge). A desktop tool is available for viewing and querying JSON log files in the same way as the built-in Log Viewer in Umbraco.

16/umbraco-cms/fundamentals/code/debugging/logging.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,10 @@ Serilog uses levels as the primary means for assigning importance to log events.
117117

118118
Serilog can be configured and extended by using the .NET Core configuration such as the AppSetting.json files or environment variables. For more information, see the [Serilog config](../../../reference/configuration/serilog.md) article.
119119

120+
## The UmbracoFile Sink
121+
122+
Serilog uses the concept of Sinks to output the log messages to different places. Umbraco ships with a custom sink configuration called UmbracoFile that uses the [Serilog.Sinks.File](https://github.com/serilog/serilog-sinks-file) sink. This will save the logs to a rolling file on disk. You can disable this sink by setting its Enabled configuration flag to false, see [Serilog config](../../../reference/configuration/serilog.md) for more information.
123+
120124
## The logviewer dashboard
121125

122126
Learn more about the [logviewer dashboard](../../backoffice/logviewer.md) in the backoffice and how it can be extended.

16/umbraco-cms/fundamentals/setup/server-setup/running-umbraco-in-docker.md

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -8,45 +8,49 @@ Docker is a platform for developing, shipping, and running applications in conta
88

99
## The Docker file system
1010

11-
By default, files created inside a container are written to an ephemeral, writable container layer.
11+
By default, files created inside a container are written to an ephemeral, writable container layer.
1212
This means that the files don't persist when the container is removed, and it's challenging to get files out of the container. Additionally, this writable layer is not suitable for performance-critical data processing.
1313

1414
This has implications when running Umbraco in Docker.
1515

1616
For more information, refer to the [Docker documentation on storage](https://docs.docker.com/engine/storage/).
1717

18-
### General file system consideration
18+
### General file system consideration
1919

2020
In general, when working with files and Docker you work in a "push" fashion with read-only layers. When you build, you take all your files and "push" them into this read-only layer.
2121

2222
This means that you should avoid making files on the fly, and instead rely on building your image.
2323

24-
In an Umbraco context, this means you should not create or edit template, script or stylesheet files via the backoffice. These should be deployed as part of your web application and not managed via Umbraco.
24+
In an Umbraco context, this means you should not create or edit template, script or stylesheet files via the backoffice. These should be deployed as part of your web application and not managed via Umbraco.
2525

2626
Similarly, you shouldn't use InMemory modelsbuilder, since that also relies on creating files on the disk. While this is not a hard requirement, it doesn't provide any value unless you are live editing your site.
2727

2828
Instead, configure models builder to use "source code" mode in development, and "none" in production, as [described when using runtime modes](https://docs.umbraco.com/umbraco-cms/fundamentals/setup/server-setup/runtime-modes).
2929

30-
3130
### Logs
3231

33-
Umbraco writes logs to the `/umbraco/Logs/` directory. Due to the performance implications of writing to a writable layer,
34-
and the limited size, it is recommended to mount a volume to this directory.
32+
Umbraco writes logs to the `/umbraco/Logs/` directory. Due to the performance implications of writing to a writable layer, and the limited size, it is recommended to mount a volume to this directory.
33+
34+
You may prefer to avoid writing to disk for logs when hosting in containers. If so, you can disable this default behavior and register a custom Serilog sink to alternative storage, such as Azure Table storage.
35+
36+
You can also provide an alternative implementation of a common abstraction for the log viewer. In this way you can read logs from the location where you have configured them to be written.
37+
38+
For more on this please read the article on Umbraco's [log viewer](../../backoffice/logviewer.md).
3539

3640
### Data
3741

3842
The `/umbraco/Data/` directory is used to store temporary files, such as file uploads. Considering the limitations of the writable layer, you should also mount a volume to this directory.
3943

4044
### Media
4145

42-
It's recommended to not store media in the writable layer. This is for similar performance reasons as logs,
43-
but also for practical hosting reasons. You likely want to persist media files between containers.
46+
It's recommended to not store media in the writable layer. This is for similar performance reasons as logs,
47+
but also for practical hosting reasons. You likely want to persist media files between containers.
4448

4549
One solution is to use bind mounts. The ideal setup, though, is to store the media and ImageSharp cache externally. For more information, refer to the [Azure Blob Storage documentation](https://docs.umbraco.com/umbraco-cms/extending/filesystemproviders/azure-blob-storage).
4650

4751
### Required files
4852

49-
Your solution may require some specific files to run, such as license files. You will need to pass these files into the container at build time, or mount them externally.
53+
Your solution may require some specific files to run, such as license files. You will need to pass these files into the container at build time, or mount them externally.
5054

5155
## HTTPS
5256

16/umbraco-cms/reference/configuration/serilog.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,7 @@ By default, Umbraco uses a special Serilog 'sink' that is optimized for performa
105105
{
106106
"Name": "UmbracoFile",
107107
"Args": {
108+
"Enabled": "True",
108109
"RestrictedToMinimumLevel": "Warning",
109110
"FileSizeLimitBytes": 1073741824,
110111
"RollingInterval" : "Day",
@@ -117,6 +118,8 @@ By default, Umbraco uses a special Serilog 'sink' that is optimized for performa
117118
}
118119
```
119120

121+
You can also disable this sink if you do not wish to write files to disk.
122+
120123
## Adding a custom log property to all log items
121124

122125
You may wish to add a log property to all log messages. A good example could be a log property for the `environment` to determine if the log message came from `development` or `production`.

0 commit comments

Comments
 (0)