Skip to content

Merge #1

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 84 commits into from
Aug 6, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
84 commits
Select commit Hold shift + click to select a range
5336190
Merge branch 'EamonHetherton-dev' into dev
nblumhardt Nov 14, 2016
1b029c8
PR code review items from #23
nblumhardt Nov 14, 2016
77eed1b
Dev version bump [Skip CI]
nblumhardt Nov 15, 2016
bce2b62
Fixes https://github.com/serilog/serilog-sinks-rollingfile/issues/37 …
nblumhardt Nov 24, 2016
06e457a
Sharing on netstandard1.3; dispose _mutex; ten second timeout waiting…
nblumhardt Nov 24, 2016
b023427
Handle AbandonedMutexException(); exclude path separator char for Linux
nblumhardt Nov 25, 2016
2c96836
Merge pull request #27 from nblumhardt/sharing-mutex
nblumhardt Nov 27, 2016
4d94c35
Dev version bump to 3.2 - new functionality
nblumhardt Nov 27, 2016
256536b
enable travis ci
Nov 27, 2016
d5b2fa3
Merge pull request #28 from skomis-mm/travis
nblumhardt Nov 29, 2016
db2cbe1
Dropped in the Travis build badge [Skip CI]
nblumhardt Nov 29, 2016
5a1519e
Execute permissions on build.sh.
merbla Nov 29, 2016
8c866ab
Merge pull request #29 from merbla/dev
nblumhardt Nov 29, 2016
ffe253f
Dev version bump [Skip CI]
nblumhardt Jan 3, 2017
ade7acd
Update README.md
xakep139 May 15, 2017
0639f1e
Merge pull request #33 from xakep139/patch-1
nblumhardt May 15, 2017
b8986cb
Rolling WIP
nblumhardt Oct 11, 2017
7614553
WIP
nblumhardt Oct 13, 2017
f04c568
Tests pass
nblumhardt Oct 13, 2017
937cdfe
Updated build scripts
nblumhardt Oct 13, 2017
b2f2c26
Attempt to fix Travis build by blindly importing the scripts and conf…
nblumhardt Oct 13, 2017
bf2060d
Review feedback
nblumhardt Oct 16, 2017
2c16619
Travis .NET tooling version
nblumhardt Oct 16, 2017
ce534dc
Run .NET Core 2.0 as test target on Travis, since that's the tooling …
nblumhardt Oct 16, 2017
c36a0ea
Temp folder location on Linux
nblumhardt Oct 16, 2017
6988cb4
Use test paths that are happy on Linux
nblumhardt Oct 16, 2017
0b514f2
Proper path concatenation in tests
nblumhardt Oct 16, 2017
e17e37e
Directory listing ordering
nblumhardt Oct 16, 2017
638a932
Return some more useful info on test failure
nblumhardt Oct 16, 2017
6f20742
Might as well be more exact on this assertion
nblumhardt Oct 16, 2017
4605f0c
More test twiddling
nblumhardt Oct 16, 2017
20423c3
Surprisingly, _ sorts before . by default on Ubuntu 16.04
nblumhardt Oct 16, 2017
b183ea4
Use VB.NET indexing for months and days ;-)
nblumhardt Oct 16, 2017
483e4e8
Tests for interval/checkpoint calculation
nblumhardt Oct 16, 2017
6ad69c1
Bring the README quality into line with the rolling file sink's
nblumhardt Oct 16, 2017
af88bce
Might as well not specify -Pre in the installation instructions, unli…
nblumhardt Oct 16, 2017
d636b08
Merge pull request #35 from nblumhardt/rolling
nblumhardt Oct 16, 2017
3e0510c
Use Serilog.Formatting.Compact in JSON example [Skip CI]
nblumhardt Oct 16, 2017
f197183
Dev version bump [Skip CI]
nblumhardt Oct 30, 2017
55c5aa2
Renamed `pathFormat` to correct `path` in example - #38 [Skip CI]
nblumhardt Oct 30, 2017
b8bb2cc
Fix link to nuget package page
tsimbalar Nov 29, 2017
0c2e485
Docs: Fix level output in default format
bbrandt Feb 21, 2018
069f0f7
Merge pull request #50 from bbrandt/patch-1
nblumhardt Feb 21, 2018
56b3753
Try to fit the example output template within the margins [Skip CI]
nblumhardt Feb 22, 2018
9fe9c0d
Fix remaining reference to RollingFile sink
tsimbalar Mar 5, 2018
27739bb
Merge pull request #52 from serilog/readme-rollingfile
nblumhardt Mar 6, 2018
f18cb0e
New NuGet API Key
merbla May 9, 2018
37a2bfe
fixing repository url
MaximRouiller Sep 21, 2018
543d861
Merge pull request #62 from MaximRouiller/repositoryurl
nblumhardt Sep 21, 2018
9903036
add SourceLink support
Nov 3, 2018
1270a76
move SourceLink configuration from Directory.Build.prop into csproj;
Nov 14, 2018
d2856bf
Merge pull request #65 from lrushl/sourcelink-support
nblumhardt Nov 15, 2018
b952e33
Add target for .net standard 2.0
Jan 10, 2019
195f959
Remove System.IO and System.IO.FileSystem.Primitives from dependencies
Jan 14, 2019
b472fc8
Update minor version to reflect added capability
nblumhardt Jan 17, 2019
ab9fc9f
Merge pull request #76 from vhatsura/netstandard20_target
nblumhardt Jan 17, 2019
f7bfe4e
Enabled FileSink and RollingFileSink's output stream in another strea…
cocowalla Feb 1, 2019
9eee731
Rename StreamWrapper to FileLifecycleHooks
cocowalla Feb 14, 2019
83d817f
Ignore Rider cache/options files
cocowalla Feb 14, 2019
63c3601
Add docs re wrapped stream ownership
cocowalla Feb 14, 2019
fca6eb9
Check for directory existence before attempting access.
billrob Mar 12, 2019
0c65484
Merge pull request #88 from billrob/dev
nblumhardt Mar 13, 2019
e604418
Improve log message when FileLifecycleHooks provided for a shared log…
cocowalla Apr 20, 2019
873f6d4
Throw clear exception when wrapping the output stream returns null
cocowalla Apr 20, 2019
e310ab9
Throw when using hooks with a shared file
cocowalla Apr 20, 2019
1864db1
Merge branch 'feature/stream-wrapper' of https://github.com/cocowalla…
nblumhardt Apr 22, 2019
b660b51
Make FileSink constructor changes non-breaking; fix a bug whereby a s…
nblumhardt Apr 22, 2019
b904968
Reenable an old test that was lost
nblumhardt Apr 22, 2019
b6090cc
A test for the encoding fix
nblumhardt Apr 22, 2019
34344ad
Move FileLifecycleHooks down under Serilog.Sinks.File - avoids namesp…
nblumhardt Apr 22, 2019
0ae234e
Enable hooks and encoding for auditing methods
nblumhardt Apr 22, 2019
55fcb2b
Add backwards-compatible configuration overloads
nblumhardt Apr 22, 2019
d4fa80a
Expose encoding to OnOpened() hook; switch to AppVeyor Linux builds
nblumhardt Apr 22, 2019
9f7352d
Fix Linux build script targets
nblumhardt Apr 22, 2019
ca0ac8c
Test for header writing
nblumhardt Apr 22, 2019
5b3d64a
OnOpened() -> OnFileOpened()
nblumhardt Apr 22, 2019
36381f6
Merge pull request #80 from cocowalla/feature/stream-wrapper
nblumhardt Apr 22, 2019
e420a36
Small clarification of size limiting behavior [skip ci]
nblumhardt Apr 22, 2019
9f8bfc3
Update NuGet API Key
merbla May 2, 2019
57d96c2
Add OnFileRemoving life cycle hook #106
Jul 8, 2019
4f1ae37
OnFileRemoving will not interfere with Serilog delete
Jul 10, 2019
735efa9
Update naming and summaries
Jul 12, 2019
f6d1cff
Add test
Jul 15, 2019
9a0257e
Merge pull request #107 from nogard111/OnFileRemovingHook
nblumhardt Jul 16, 2019
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion .editorconfig
Original file line number Diff line number Diff line change
@@ -1,5 +1,16 @@
root=true
root = true

[*]
trim_trailing_whitespace = true
insert_final_newline = true
indent_style = space
indent_size = 4

[*.{csproj,json,config,yml,props}]
indent_size = 2

[*.sh]
end_of_line = lf

[*.{cmd, bat}]
end_of_line = crlf
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@ bld/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/

# Rider cache/options directory
.idea

# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
Expand Down Expand Up @@ -234,3 +237,4 @@ _Pvt_Extensions

# FAKE - F# Make
.fake/
example/Sample/log.txt
11 changes: 11 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
language: csharp

matrix:
include:
- os: linux
dist: trusty
sudo: required
dotnet: 2.1.300
group: edge
script:
- ./build.sh
31 changes: 25 additions & 6 deletions Build.ps1
Original file line number Diff line number Diff line change
@@ -1,27 +1,46 @@
echo "build: Build started"

Push-Location $PSScriptRoot

if(Test-Path .\artifacts) { Remove-Item .\artifacts -Force -Recurse }
if(Test-Path .\artifacts) {
echo "build: Cleaning .\artifacts"
Remove-Item .\artifacts -Force -Recurse
}

& dotnet restore --no-cache

$branch = @{ $true = $env:APPVEYOR_REPO_BRANCH; $false = $(git symbolic-ref --short -q HEAD) }[$env:APPVEYOR_REPO_BRANCH -ne $NULL];
$revision = @{ $true = "{0:00000}" -f [convert]::ToInt32("0" + $env:APPVEYOR_BUILD_NUMBER, 10); $false = "local" }[$env:APPVEYOR_BUILD_NUMBER -ne $NULL];
$suffix = @{ $true = ""; $false = "$branch-$revision"}[$branch -eq "master" -and $revision -ne "local"]
$suffix = @{ $true = ""; $false = "$($branch.Substring(0, [math]::Min(10,$branch.Length)))-$revision"}[$branch -eq "master" -and $revision -ne "local"]
$commitHash = $(git rev-parse --short HEAD)
$buildSuffix = @{ $true = "$($suffix)-$($commitHash)"; $false = "$($branch)-$($commitHash)" }[$suffix -ne ""]

echo "build: Package version suffix is $suffix"
echo "build: Build version suffix is $buildSuffix"

foreach ($src in ls src/Serilog.*) {
foreach ($src in ls src/*) {
Push-Location $src

& dotnet pack -c Release -o ..\..\.\artifacts --version-suffix=$suffix
echo "build: Packaging project in $src"

& dotnet build -c Release --version-suffix=$buildSuffix -p:EnableSourceLink=true
if ($suffix) {
& dotnet pack -c Release -o ..\..\artifacts --version-suffix=$suffix --no-build
} else {
& dotnet pack -c Release -o ..\..\artifacts --no-build
}
if($LASTEXITCODE -ne 0) { exit 1 }

Pop-Location
}

foreach ($test in ls test/Serilog.*.Tests) {
foreach ($test in ls test/*.Tests) {
Push-Location $test

echo "build: Testing project in $test"

& dotnet test -c Release
if($LASTEXITCODE -ne 0) { exit 2 }
if($LASTEXITCODE -ne 0) { exit 3 }

Pop-Location
}
Expand Down
173 changes: 158 additions & 15 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,53 +1,196 @@
# Serilog.Sinks.File [![Build status](https://ci.appveyor.com/api/projects/status/hh9gymy0n6tne46j?svg=true)](https://ci.appveyor.com/project/serilog/serilog-sinks-file) [![NuGet Version](http://img.shields.io/nuget/v/Serilog.Sinks.File.svg?style=flat)](https://www.nuget.org/packages/Serilog.Sinks.File/) [![Documentation](https://img.shields.io/badge/docs-wiki-yellow.svg)](https://github.com/serilog/serilog/wiki) [![Join the chat at https://gitter.im/serilog/serilog](https://img.shields.io/gitter/room/serilog/serilog.svg)](https://gitter.im/serilog/serilog)

Writes [Serilog](https://serilog.net) events to a text file.
Writes [Serilog](https://serilog.net) events to one or more text files.

### Getting started

Install the [Serilog.Sinks.File](https://www.nuget.org/packages/Serilog.Sinks.File/) package from NuGet:

```powershell
Install-Package Serilog.Sinks.File
```

To configure the sink in C# code, call `WriteTo.File()` during logger configuration:

```csharp
var log = new LoggerConfiguration()
.WriteTo.File("log.txt")
.WriteTo.File("log.txt", rollingInterval: RollingInterval.Day)
.CreateLogger();
```

To avoid bringing down apps with runaway disk usage the file sink **limits file size to 1GB by default**. The limit can be increased or removed using the `fileSizeLimitBytes` parameter.
This will append the time period to the filename, creating a file set like:

```
log20180631.txt
log20180701.txt
log20180702.txt
```

> **Important**: By default, only one process may write to a log file at a given time. See _Shared log files_ below for information on multi-process sharing.

### Limits

To avoid bringing down apps with runaway disk usage the file sink **limits file size to 1GB by default**. Once the limit is reached, no further events will be written until the next roll point (see also: [Rolling policies](#rolling-policies) below).

The limit can be changed or removed using the `fileSizeLimitBytes` parameter.

```csharp
.WriteTo.File("log.txt", fileSizeLimitBytes: null)
```

For the same reason, only **the most recent 31 files** are retained by default (i.e. one long month). To change or remove this limit, pass the `retainedFileCountLimit` parameter.

```csharp
.WriteTo.File("log.txt", rollingInterval: RollingInterval.Day, retainedFileCountLimit: null)
```

### Rolling policies

To create a log file per day or other time period, specify a `rollingInterval` as shown in the examples above.

To roll when the file reaches `fileSizeLimitBytes`, specify `rollOnFileSizeLimit`:

```csharp
.WriteTo.File("log.txt", rollOnFileSizeLimit: true)
```

This will create a file set like:

```
log.txt
log_001.txt
log_002.txt
```

Specifying both `rollingInterval` and `rollOnFileSizeLimit` will cause both policies to be applied, while specifying neither will result in all events being written to a single file.

Old files will be cleaned up as per `retainedFileCountLimit` - the default is 31.

### XML `<appSettings>` configuration

To use the file sink with the [Serilog.Settings.AppSettings](https://github.com/serilog/serilog-settings-appsettings) package, first install that package if you haven't already done so:

```powershell
Install-Package Serilog.Settings.AppSettings
```

Instead of configuring the logger in code, call `ReadFrom.AppSettings()`:

```csharp
var log = new LoggerConfiguration()
.ReadFrom.AppSettings()
.CreateLogger();
```

In your application's `App.config` or `Web.config` file, specify the file sink assembly and required path format under the `<appSettings>` node:

```xml
<configuration>
<appSettings>
<add key="serilog:using:File" value="Serilog.Sinks.File" />
<add key="serilog:write-to:File.path" value="log.txt" />
```

The parameters that can be set through the `serilog:write-to:File` keys are the method parameters accepted by the `WriteTo.File()` configuration method. This means, for example, that the `fileSizeLimitBytes` parameter can be set with:

```xml
<add key="serilog:write-to:File.fileSizeLimitBytes" value="1234567" />
```

> **Important:** By default only one process may use a log file at a given time. See _Shared log files_ below if multi-process logging is required.
Omitting the `value` will set the parameter to `null`:

### `<appSettings>` configuration
```xml
<add key="serilog:write-to:File.fileSizeLimitBytes" />
```

The sink can be configured in XML [app-settings format](https://github.com/serilog/serilog/wiki/AppSettings) if the _Serilog.Settings.AppSettings_ package is in use:
In XML and JSON configuration formats, environment variables can be used in setting values. This means, for instance, that the log file path can be based on `TMP` or `APPDATA`:

```xml
<add key="serilog:using:File" value="Serilog.Sinks.File" />
<add key="serilog:write-to:File.path" value="log.txt" />
<add key="serilog:write-to:File.fileSizeLimitBytes" value="" />
<add key="serilog:write-to:File.path" value="%APPDATA%\MyApp\log.txt" />
```

### JSON `appsettings.json` configuration

To use the file sink with _Microsoft.Extensions.Configuration_, for example with ASP.NET Core or .NET Core, use the [Serilog.Settings.Configuration](https://github.com/serilog/serilog-settings-configuration) package. First install that package if you have not already done so:

```powershell
Install-Package Serilog.Settings.Configuration
```

Instead of configuring the file directly in code, call `ReadFrom.Configuration()`:

```csharp
var configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.Build();

var logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();
```

### JSON formatting
In your `appsettings.json` file, under the `Serilog` node, :

To emit JSON, rather than plain text, a formatter can be specified:
```json
{
"Serilog": {
"WriteTo": [
{ "Name": "File", "Args": { "path": "log.txt", "rollingInterval": "Day" } }
]
}
}
```

See the XML `<appSettings>` example above for a discussion of available `Args` options.

### Controlling event formatting

The file sink creates events in a fixed text format by default:

```
2018-07-06 09:02:17.148 +10:00 [INF] HTTP GET / responded 200 in 1994 ms
```

The format is controlled using an _output template_, which the file configuration method accepts as an `outputTemplate` parameter.

The default format above corresponds to an output template like:

```csharp
.WriteTo.File(new JsonFormatter(), "log.txt")
.WriteTo.File("log.txt",
outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}")
```

To configure an alternative formatter in XML `<appSettings>`, specify the formatter's assembly-qualified type name as the setting `value`.
##### JSON event formatting

To write events to the file in an alternative format such as [JSON](https://github.com/serilog/serilog-formatting-compact), pass an `ITextFormatter` as the first argument:

```csharp
// Install-Package Serilog.Formatting.Compact
.WriteTo.File(new CompactJsonFormatter(), "log.txt")
```

### Shared log files

Multiple processes can concurrently write to the same log file if the `shared` parameter is set to `true`:
To enable multi-process shared log files, set `shared` to `true`:

```csharp
.WriteTo.File("log.txt", shared: true)
```

### Auditing

The file sink can operate as an audit file through `AuditTo`:

```csharp
.AuditTo.File("audit.txt")
```

Only a limited subset of configuration options are currently available in this mode.

### Performance

By default, the file sink will flush each event written through it to disk. To improve write performance, specifying `buffered: true` will permit the underlying stream to buffer writes.

The [Serilog.Sinks.Async](https://github.com/serilog/serilog-sinks-async) package can be used to wrap the file sink and perform all disk accss on a background worker thread.
The [Serilog.Sinks.Async](https://github.com/serilog/serilog-sinks-async) package can be used to wrap the file sink and perform all disk access on a background worker thread.

_Copyright &copy; 2016 Serilog Contributors - Provided under the [Apache License, Version 2.0](http://apache.org/licenses/LICENSE-2.0.html)._
19 changes: 11 additions & 8 deletions appveyor.yml
Original file line number Diff line number Diff line change
@@ -1,22 +1,25 @@
version: '{build}'
skip_tags: true
image: Visual Studio 2015
image:
- Visual Studio 2017
- Ubuntu
configuration: Release
install:
- ps: mkdir -Force ".\build\" | Out-Null
- ps: Invoke-WebRequest "https://raw.githubusercontent.com/dotnet/cli/rel/1.0.0-preview2/scripts/obtain/dotnet-install.ps1" -OutFile ".\build\installcli.ps1"
- ps: $env:DOTNET_INSTALL_DIR = "$pwd\.dotnetcli"
- ps: '& .\build\installcli.ps1 -InstallDir "$env:DOTNET_INSTALL_DIR" -NoPath -Version 1.0.0-preview2-003121'
- ps: $env:Path = "$env:DOTNET_INSTALL_DIR;$env:Path"
build_script:
- ps: ./Build.ps1
for:
-
matrix:
only:
- image: Ubuntu
build_script:
- sh build.sh
test: off
artifacts:
- path: artifacts/Serilog.*.nupkg
deploy:
- provider: NuGet
api_key:
secure: nvZ/z+pMS91b3kG4DgfES5AcmwwGoBYQxr9kp4XiJHj25SAlgdIxFx++1N0lFH2x
secure: N59tiJECUYpip6tEn0xvdmDAEiP9SIzyLEFLpwiigm/8WhJvBNs13QxzT1/3/JW/
skip_symbols: true
on:
branch: /^(master|dev)$/
Expand Down
17 changes: 17 additions & 0 deletions build.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
#!/bin/bash

set -e
dotnet --info
dotnet --list-sdks
dotnet restore

echo "🤖 Attempting to build..."
for path in src/**/*.csproj; do
dotnet build -f netstandard1.3 -c Release ${path}
dotnet build -f netstandard2.0 -c Release ${path}
done

echo "🤖 Running tests..."
for path in test/*.Tests/*.csproj; do
dotnet test -f netcoreapp2.0 -c Release ${path}
done
4 changes: 2 additions & 2 deletions example/Sample/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,12 @@ public static void Main(string[] args)
{
SelfLog.Enable(Console.Out);

var sw = System.Diagnostics.Stopwatch.StartNew();

Log.Logger = new LoggerConfiguration()
.WriteTo.File("log.txt")
.CreateLogger();

var sw = System.Diagnostics.Stopwatch.StartNew();

for (var i = 0; i < 1000000; ++i)
{
Log.Information("Hello, file logger!");
Expand Down
Loading