Compare commits

..

15 commits

Author SHA1 Message Date
67c21299a6
go.mod: Tidy
Signed-off-by: Evgenii Stratonikov <e.stratonikov@yadro.com>
2024-10-25 13:41:05 +03:00
cb2e66427d [#15] Fix partial encoder bench
'benchmarkLog' and 'benchmarkEncoder'
are pretty much the same, but it can
be changed later.

Signed-off-by: Alex Vanin <a.vanin@yadro.com>
2024-01-24 14:42:43 +03:00
045b966ecb [#15] Add partial encoder
Partial encoder is an encoder wrapper which
ignores specific fields. This is useful with
zapjournald core to ignore syslog fields
in human-readable console output.

Encoder adds almost none overhead and even improves
logging speed for entities with syslog fields.

Signed-off-by: Alex Vanin <a.vanin@yadro.com>
2024-01-23 19:47:34 +03:00
2b6d84de9a [#12] Optimize field encoding a bit
No need to clone a map if it is empty.

Signed-off-by: Evgenii Stratonikov <e.stratonikov@yadro.com>
2023-10-18 11:30:19 +03:00
f358e67c81 [#12] Fix int-like fields encoding
Do it in journal similar to how we do it in zap.
1. Duration should take the form of "12s".
2. Uint64 should be encoded without sign.
3. Bool is better be true/false instead of 0/1.
4. Float64 should be float, not IEEE 754 bits cast to int64.

Signed-off-by: Evgenii Stratonikov <e.stratonikov@yadro.com>
2023-10-18 11:30:09 +03:00
8d45f23fcd [#12] Rename file with syslog fields
Signed-off-by: Evgenii Stratonikov <e.stratonikov@yadro.com>
2023-10-18 11:30:05 +03:00
d6ea4d0bbf [#12] Use buffer pool for message encoding
```
goos: linux
goarch: amd64
pkg: git.frostfs.info/TrueCloudLab/zapjournald
cpu: 11th Gen Intel(R) Core(TM) i5-1135G7 @ 2.40GHz
                                     │      1       │                  2                  │
                                     │    sec/op    │   sec/op     vs base                │
Logger/standard/no_fields-8             450.3n ± 2%   452.9n ± 3%        ~ (p=0.138 n=10)
Logger/standard/application_fields-8    610.4n ± 1%   608.4n ± 1%        ~ (p=0.325 n=10)
Logger/standard/journald_fields-8       595.8n ± 5%   604.5n ± 1%        ~ (p=0.075 n=10)
Logger/journald/no_fields-8            1809.0n ± 4%   900.4n ± 1%  -50.23% (p=0.000 n=10)
Logger/journald/application_fields-8    2.037µ ± 5%   1.087µ ± 1%  -46.62% (p=0.000 n=10)
Logger/journald/journald_fields-8       2.054µ ± 4%   1.119µ ± 1%  -45.52% (p=0.000 n=10)
geomean                                 1.036µ        753.1n       -27.33%

                                     │        1        │                  2                   │
                                     │      B/op       │    B/op     vs base                  │
Logger/standard/no_fields-8               0.000 ± 0%     0.000 ± 0%        ~ (p=1.000 n=10) ¹
Logger/standard/application_fields-8      128.0 ± 0%     128.0 ± 0%        ~ (p=1.000 n=10) ¹
Logger/standard/journald_fields-8         64.00 ± 0%     64.00 ± 0%        ~ (p=1.000 n=10) ¹
Logger/journald/no_fields-8            1206.000 ± 0%     5.000 ± 0%  -99.59% (p=0.000 n=10)
Logger/journald/application_fields-8     1494.0 ± 0%     133.0 ± 0%  -91.10% (p=0.000 n=10)
Logger/journald/journald_fields-8       1478.00 ± 0%     85.00 ± 0%  -94.25% (p=0.000 n=10)
geomean                                              ²               -83.36%                ²
¹ all samples are equal
² summaries must be >0 to compute geomean

                                     │       1       │                  2                   │
                                     │   allocs/op   │ allocs/op   vs base                  │
Logger/standard/no_fields-8             0.000 ± 0%     0.000 ± 0%        ~ (p=1.000 n=10) ¹
Logger/standard/application_fields-8    1.000 ± 0%     1.000 ± 0%        ~ (p=1.000 n=10) ¹
Logger/standard/journald_fields-8       1.000 ± 0%     1.000 ± 0%        ~ (p=1.000 n=10) ¹
Logger/journald/no_fields-8            29.000 ± 0%     1.000 ± 0%  -96.55% (p=0.000 n=10)
Logger/journald/application_fields-8   30.000 ± 0%     2.000 ± 0%  -93.33% (p=0.000 n=10)
Logger/journald/journald_fields-8      31.000 ± 0%     3.000 ± 0%  -90.32% (p=0.000 n=10)
geomean                                            ²               -75.38%                ²
¹ all samples are equal
² summaries must be >0 to compute geomean
```

Signed-off-by: Evgenii Stratonikov <e.stratonikov@yadro.com>
2023-10-18 11:30:00 +03:00
8c4cf38d6a [#12] Free internal encoder buffer
```
goos: linux
goarch: amd64
pkg: git.frostfs.info/TrueCloudLab/zapjournald
cpu: 11th Gen Intel(R) Core(TM) i5-1135G7 @ 2.40GHz
                                     │     old     │                  1                  │
                                     │   sec/op    │   sec/op     vs base                │
Logger/standard/no_fields-8            435.9n ± 4%   450.3n ± 2%   +3.30% (p=0.041 n=10)
Logger/standard/application_fields-8   629.0n ± 8%   610.4n ± 1%   -2.96% (p=0.002 n=10)
Logger/standard/journald_fields-8      626.8n ± 5%   595.8n ± 5%   -4.95% (p=0.029 n=10)
Logger/journald/no_fields-8            2.097µ ± 3%   1.809µ ± 4%  -13.73% (p=0.000 n=10)
Logger/journald/application_fields-8   2.348µ ± 5%   2.037µ ± 5%  -13.27% (p=0.000 n=10)
Logger/journald/journald_fields-8      2.396µ ± 4%   2.054µ ± 4%  -14.26% (p=0.000 n=10)
geomean                                1.125µ        1.036µ        -7.88%

                                     │      old       │                   1                    │
                                     │      B/op      │     B/op      vs base                  │
Logger/standard/no_fields-8              0.000 ± 0%       0.000 ± 0%        ~ (p=1.000 n=10) ¹
Logger/standard/application_fields-8     128.0 ± 0%       128.0 ± 0%        ~ (p=1.000 n=10) ¹
Logger/standard/journald_fields-8        64.00 ± 0%       64.00 ± 0%        ~ (p=1.000 n=10) ¹
Logger/journald/no_fields-8            2.210Ki ± 0%     1.178Ki ± 0%  -46.71% (p=0.000 n=10)
Logger/journald/application_fields-8   2.491Ki ± 0%     1.459Ki ± 0%  -41.43% (p=0.000 n=10)
Logger/journald/journald_fields-8      2.476Ki ± 0%     1.443Ki ± 0%  -41.70% (p=0.000 n=10)
geomean                                             ²                 -24.72%                ²
¹ all samples are equal
² summaries must be >0 to compute geomean

                                     │     old      │                  1                  │
                                     │  allocs/op   │ allocs/op   vs base                 │
Logger/standard/no_fields-8            0.000 ± 0%     0.000 ± 0%       ~ (p=1.000 n=10) ¹
Logger/standard/application_fields-8   1.000 ± 0%     1.000 ± 0%       ~ (p=1.000 n=10) ¹
Logger/standard/journald_fields-8      1.000 ± 0%     1.000 ± 0%       ~ (p=1.000 n=10) ¹
Logger/journald/no_fields-8            31.00 ± 0%     29.00 ± 0%  -6.45% (p=0.000 n=10)
Logger/journald/application_fields-8   32.00 ± 0%     30.00 ± 0%  -6.25% (p=0.000 n=10)
Logger/journald/journald_fields-8      33.00 ± 0%     31.00 ± 0%  -6.06% (p=0.000 n=10)
geomean                                           ²               -3.18%                ²
¹ all samples are equal
² summaries must be >0 to compute geomean
```

Signed-off-by: Evgenii Stratonikov <e.stratonikov@yadro.com>
2023-10-18 11:29:55 +03:00
49c42ba807 [#12] Move log level conversion to a function
Signed-off-by: Evgenii Stratonikov <e.stratonikov@yadro.com>
2023-10-18 11:29:53 +03:00
b9d389933b [#12] Add benchmarks
Signed-off-by: Evgenii Stratonikov <e.stratonikov@yadro.com>
2023-10-18 11:29:40 +03:00
a6eb2f6261 [#10] Add basic templates for repository
Signed-off-by: Aleksey Savaitan <a.savaitan@yadro.com>
2023-04-17 11:21:21 +03:00
9432aa2d73 [#2] Add license file
Signed-off-by: Aleksey Savaitan <a.savaitan@yadro.com>
2023-04-17 06:54:55 +00:00
4c6e1f7365 [#7] Fix comment lexical
Signed-off-by: Aleksey Savaitan <a.savaitan@yadro.com>
2023-04-14 11:00:36 +03:00
f3f6f54b15 [#7] Add small test for getFieldValue function
Signed-off-by: Aleksey Savaitan <a.savaitan@yadro.com>
2023-04-14 11:00:07 +03:00
Aleksey Savaitan
074fe474dd [#3] Initial implementation
Signed-off-by: Aleksey Savaitan <zxc_off@mail.ru>
2023-04-10 15:35:42 +03:00
16 changed files with 1230 additions and 17 deletions

50
.gitignore vendored Normal file
View file

@ -0,0 +1,50 @@
# IDE
.idea
.vscode
# Vendoring
vendor
# tempfiles
.DS_Store
*~
.cache
temp
tmp
# binary
bin/
release/
# coverage
coverage.txt
coverage.html
# testing
cmd/test
/plugins/
testfile
# misc
# debhelpers
debian/*debhelper*
# logfiles
debian/*.log
# .substvars
debian/*.substvars
# .bash-completion
debian/*.bash-completion
# Install folders and files
debian/frostfs-cli/
debian/frostfs-ir/
debian/files
debian/frostfs-storage/
debian/changelog
man/
debs/

11
.gitlint Normal file
View file

@ -0,0 +1,11 @@
[general]
fail-without-commits=True
regex-style-search=True
contrib=CC1
[title-match-regex]
regex=^\[\#[0-9Xx]+\]\s
[ignore-by-title]
regex=^Release(.*)
ignore=title-match-regex

View file

@ -4,10 +4,10 @@
# options for analysis running
run:
# timeout for analysis, e.g. 30s, 5m, default is 1m
timeout: 5m
timeout: 10m
# include test files or not, default is true
tests: true
tests: false
# output configuration options
output:
@ -24,6 +24,13 @@ linters-settings:
govet:
# report about shadowed variables
check-shadowing: false
staticcheck:
checks: ["all", "-SA1019"] # TODO Enable SA1019 after deprecated warning are fixed.
funlen:
lines: 80 # default 60
statements: 60 # default 40
gocognit:
min-complexity: 40 # default 30
linters:
enable:
@ -34,23 +41,26 @@ linters:
# some default golangci-lint linters
- errcheck
- gosimple
- godot
- ineffassign
- staticcheck
- typecheck
- unused
# extra linters
- bidichk
- durationcheck
- exhaustive
- godot
- exportloopref
- gofmt
- whitespace
- goimports
- misspell
- predeclared
- reassign
- whitespace
- containedctx
- funlen
- gocognit
- contextcheck
disable-all: true
fast: false
issues:
include:
- EXC0002 # should have a comment
- EXC0003 # test/Test ... consider calling this
- EXC0004 # govet
- EXC0005 # C-style breaks

View file

@ -34,3 +34,12 @@ repos:
rev: v1.51.2
hooks:
- id: golangci-lint
- repo: local
hooks:
- id: go-unit-tests
name: go unit tests
entry: make test
pass_filenames: false
types: [go]
language: system

View file

@ -1,6 +0,0 @@
pipeline:
pre-commit:
image: git.frostfs.info/truecloudlab/frostfs-ci:v0.36
commands:
- export HOME="$(getent passwd $(id -u) | cut '-d:' -f6)"
- pre-commit run --hook-stage manual

201
LICENSE Normal file
View file

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

119
README.md Normal file
View file

@ -0,0 +1,119 @@
# Zap Core for systemd Journal
Package `zapjournld` provides `zap` Core for systemd Journal. It supports structured logging.
Applications may use zap logger to write logs directly into journald and may relatively freely define additional fields, which will be indexed by journald.
Information about common and custom journald fields is available on https://www.freedesktop.org/software/systemd/man/systemd.journal-fields.html.
## Example
```go
package main
import (
"fmt"
"git.frostfs.info/TrueCloudLab/zapjournald"
"go.uber.org/zap"
"github.com/ssgreg/journald"
"go.uber.org/zap/zapcore"
)
func main() {
// StandardLogger
standardLogger, _ := NewStandardLogger("info")
standardLogger.Info("Simple log raw 1")
}
func NewStandardLogger(lvlStr string) (*zap.Logger, zap.AtomicLevel) {
lvl, err := getLogLevel(lvlStr)
if err != nil {
panic(err)
}
zc := zap.NewProductionConfig()
zc.EncoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
zc.Level = zap.NewAtomicLevelAt(lvl)
// Initialize Zap.
encoder := zapcore.NewJSONEncoder(zc.EncoderConfig)
core := zapjournald.NewCore(zap.NewAtomicLevelAt(lvl), encoder, &journald.Journal{}, zapjournald.SyslogFields)
coreWithContext := core.With([]zapcore.Field{
zapjournald.SyslogFacility(zapjournald.LogDaemon),
zapjournald.SyslogIdentifier(),
zapjournald.SyslogPid(),
})
l := zap.New(coreWithContext, zap.AddStacktrace(zap.NewAtomicLevelAt(zap.FatalLevel)))
return l, zc.Level
}
func getLogLevel(lvlStr string) (zapcore.Level, error) {
var lvl zapcore.Level
err := lvl.UnmarshalText([]byte(lvlStr))
if err != nil {
return lvl, fmt.Errorf("incorrect logger level configuration %s (%v), "+
"value should be one of %v", lvlStr, err, [...]zapcore.Level{
zapcore.DebugLevel,
zapcore.InfoLevel,
zapcore.WarnLevel,
zapcore.ErrorLevel,
zapcore.DPanicLevel,
zapcore.PanicLevel,
zapcore.FatalLevel,
})
}
return lvl, nil
}
```
### Results
#### You can read simple view like this:
```
sudo journalctl -f
Apr 07 13:06:34 user ___11go_build_git_frostfs_info_TrueCloudLab_zapjournald_main[330983]: {"level":"info","ts":"2023-04-07T13:06:34.990+0300","msg":"Simple log raw 1","SYSLOG_FACILITY":3,"SYSLOG_IDENTIFIER":"___11go_build_git_frostfs_info_TrueCloudLab_zapjournald_main","SYSLOG_PID":330983}
```
#### Or you can find lines by indexed field
```
sudo journalctl SYSLOG_PID=76385
Apr 07 13:06:34 user ___11go_build_git_frostfs_info_TrueCloudLab_zapjournald_main[330983]: {"level":"info","ts":"2023-04-07T13:06:34.990+0300","msg":"Simple log raw 1","SYSLOG_FACILITY":3,"SYSLOG_ID>
```
#### Or you can read full-structured view like this:
```
sudo journalctl SYSLOG_PID=76385 --output=json-pretty
{
"PRIORITY" : "6",
"_SYSTEMD_OWNER_UID" : "1000",
"_HOSTNAME" : "user",
"__MONOTONIC_TIMESTAMP" : "153798818198",
"_SYSTEMD_SLICE" : "user-1000.slice",
"_GID" : "1000",
"_AUDIT_LOGINUID" : "1000",
"_UID" : "1000",
"SYSLOG_IDENTIFIER" : "___11go_build_git_frostfs_info_TrueCloudLab_zapjournald_main",
"__REALTIME_TIMESTAMP" : "1680861994990646",
"_CAP_EFFECTIVE" : "0",
"_COMM" : "___11go_build_g",
"_AUDIT_SESSION" : "59",
"__CURSOR" : "s=9e2d157a286a437ea3405618239c1e07;i=14a96;b=bc1bc632f462476abc9e3e3b0c517f6c;m=23cf1fb996;t=5f8bc2e20bc36;x=9c6c4a86b6da43c",
"_SYSTEMD_USER_SLICE" : "app.slice",
"_SYSTEMD_CGROUP" : "/user.slice/user-1000.slice/user@1000.service/app.slice/app-gnome-jetbrains\\x2dgoland-203587.scope",
"MESSAGE" : "{\"level\":\"info\",\"ts\":\"2023-04-07T13:06:34.990+0300\",\"msg\":\"Simple log raw 1\",\"SYSLOG_FACILITY\":3,\"SYSLOG_IDENTIFIER\":\"___11go_build_git_frostfs_info_TrueCloudLab_zapjournal>
"_SOURCE_REALTIME_TIMESTAMP" : "1680861994990539",
"_MACHINE_ID" : "82be99c92deb4b36850366d7742de698",
"SYSLOG_FACILITY" : "3",
"_BOOT_ID" : "bc1bc632f462476abc9e3e3b0c517f6c",
"_PID" : "330983",
"_SELINUX_CONTEXT" : "unconfined\n",
"_SYSTEMD_UNIT" : "user@1000.service",
"_TRANSPORT" : "journal",
"_SYSTEMD_INVOCATION_ID" : "ed23dc57a96340029ef8bf9956182c20",
"_SYSTEMD_USER_UNIT" : "app-gnome-jetbrains\\x2dgoland-203587.scope",
"SYSLOG_PID" : "330983"
}
```
# License
- [Apache License, Version 2.0](LICENSE)

65
benchmark_test.go Normal file
View file

@ -0,0 +1,65 @@
package zapjournald
import (
"testing"
"github.com/ssgreg/journald"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
type nopSync struct{}
func (nopSync) Write([]byte) (int, error) { return 0, nil }
func (nopSync) Sync() error { return nil }
func BenchmarkLogger(b *testing.B) {
zc := zap.NewProductionConfig()
zc.EncoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
zc.Level = zap.NewAtomicLevelAt(zap.InfoLevel)
b.Run("standard", func(b *testing.B) {
encoder := zapcore.NewJSONEncoder(zc.EncoderConfig)
core := zapcore.NewCore(encoder, nopSync{}, zc.Level)
coreWithContext := core.With([]zapcore.Field{
SyslogFacility(LogDaemon),
SyslogIdentifier(),
SyslogPid()})
l := zap.New(coreWithContext)
benchmarkLog(b, l)
})
b.Run("journald", func(b *testing.B) {
encoder := zapcore.NewJSONEncoder(zc.EncoderConfig)
core := NewCore(zc.Level, encoder, &journald.Journal{}, SyslogFields)
core.j.TestModeEnabled = true // Disable actual writing to the journal.
coreWithContext := core.With([]zapcore.Field{
SyslogFacility(LogDaemon),
SyslogIdentifier(),
SyslogPid(),
})
l := zap.New(coreWithContext)
benchmarkLog(b, l)
})
}
func benchmarkLog(b *testing.B, l *zap.Logger) {
b.Run("no fields", func(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
l.Info("Simple log message")
}
})
b.Run("application fields", func(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
l.Info("Simple log message", zap.Uint32("count", 123), zap.String("details", "nothing"))
}
})
b.Run("journald fields", func(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
l.Info("Simple log message", SyslogIdentifier())
}
})
}

70
encoder.go Normal file
View file

@ -0,0 +1,70 @@
package zapjournald
import (
"bytes"
"fmt"
"strings"
"go.uber.org/zap/buffer"
)
var pool = buffer.NewPool()
func encodeJournaldField(buf *buffer.Buffer, key string, value any) {
switch v := value.(type) {
case string:
writeField(buf, key, v)
case []byte:
writeFieldBytes(buf, key, v)
default:
writeField(buf, key, fmt.Sprint(v))
}
}
func writeFieldBytes(buf *buffer.Buffer, name string, value []byte) {
buf.Write([]byte(name))
if bytes.ContainsRune(value, '\n') {
// According to the format, if the value includes a newline
// need to write the field name, plus a newline, then the
// size (64bit LE), the field data and a final newline.
buf.Write([]byte{'\n'})
appendUint64Binary(buf, uint64(len(value)))
} else {
buf.Write([]byte{'='})
}
buf.Write(value)
buf.Write([]byte{'\n'})
}
func writeField(buf *buffer.Buffer, name string, value string) {
buf.Write([]byte(name))
if strings.ContainsRune(value, '\n') {
// According to the format, if the value includes a newline
// need to write the field name, plus a newline, then the
// size (64bit LE), the field data and a final newline.
buf.Write([]byte{'\n'})
// 1 allocation here.
// binary.Write(w, binary.LittleEndian, uint64(len(value)))
appendUint64Binary(buf, uint64(len(value)))
} else {
buf.Write([]byte{'='})
}
buf.WriteString(value)
buf.Write([]byte{'\n'})
}
func appendUint64Binary(buf *buffer.Buffer, v uint64) {
// Copied from https://github.com/golang/go/blob/go1.21.3/src/encoding/binary/binary.go#L119
buf.Write([]byte{
byte(v),
byte(v >> 8),
byte(v >> 16),
byte(v >> 24),
byte(v >> 32),
byte(v >> 40),
byte(v >> 48),
byte(v >> 56),
})
}

15
go.mod
View file

@ -1,3 +1,18 @@
module git.frostfs.info/TrueCloudLab/zapjournald
go 1.19
require (
github.com/ssgreg/journald v1.0.0
github.com/stretchr/testify v1.8.1
go.uber.org/zap v1.27.0
golang.org/x/exp v0.0.0-20230321023759-10a507213a29
)
require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
go.uber.org/multierr v1.10.0 // indirect
golang.org/x/sys v0.1.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)

28
go.sum Normal file
View file

@ -0,0 +1,28 @@
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/ssgreg/journald v1.0.0 h1:0YmTDPJXxcWDPba12qNMdO6TxvfkFSYpFIJ31CwmLcU=
github.com/ssgreg/journald v1.0.0/go.mod h1:RUckwmTM8ghGWPslq2+ZBZzbb9/2KgjzYZ4JEP+oRt0=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk=
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
go.uber.org/multierr v1.10.0 h1:S0h4aNzvfcFsC3dRF1jLoaov7oRaKqRGC/pUEJ2yvPQ=
go.uber.org/multierr v1.10.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
go.uber.org/zap v1.27.0 h1:aJMhYGrd5QSmlpLMr2MftRKl7t8J8PTZPA732ud/XR8=
go.uber.org/zap v1.27.0/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=
golang.org/x/exp v0.0.0-20230321023759-10a507213a29 h1:ooxPy7fPvB4kwsA2h+iBNHkAbp/4JxTSwCmvdjEYmug=
golang.org/x/exp v0.0.0-20230321023759-10a507213a29/go.mod h1:CxIveKay+FTh1D0yPZemJVgC/95VzuuOLq5Qi4xnoYc=
golang.org/x/sys v0.1.0 h1:kunALQeHf1/185U1i0GOB/fy1IPRDDpuoOOqRReG57U=
golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

214
partial_encoder.go Normal file
View file

@ -0,0 +1,214 @@
package zapjournald
import (
"time"
"go.uber.org/zap/buffer"
"go.uber.org/zap/zapcore"
"golang.org/x/exp/maps"
)
type partialEncoder struct {
wrap zapcore.Encoder
ignore map[string]struct{}
}
// NewPartialEncoder wraps existing encoder to avoid output of some provided
// fields. The main use case is to ignore SyslogFields that leak into
// ConsoleEncoder and provide no additional info for the human.
func NewPartialEncoder(enc zapcore.Encoder, ignore []string) zapcore.Encoder {
m := make(map[string]struct{}, len(ignore))
for _, i := range ignore {
m[i] = struct{}{}
}
return partialEncoder{
wrap: enc,
ignore: m,
}
}
func (enc partialEncoder) AddArray(key string, marshaler zapcore.ArrayMarshaler) error {
if _, ok := enc.ignore[key]; ok {
return nil
}
return enc.wrap.AddArray(key, marshaler)
}
func (enc partialEncoder) AddObject(key string, marshaler zapcore.ObjectMarshaler) error {
if _, ok := enc.ignore[key]; ok {
return nil
}
return enc.wrap.AddObject(key, marshaler)
}
func (enc partialEncoder) AddBinary(key string, value []byte) {
if _, ok := enc.ignore[key]; ok {
return
}
enc.wrap.AddBinary(key, value)
}
func (enc partialEncoder) AddByteString(key string, value []byte) {
if _, ok := enc.ignore[key]; ok {
return
}
enc.wrap.AddByteString(key, value)
}
func (enc partialEncoder) AddBool(key string, value bool) {
if _, ok := enc.ignore[key]; ok {
return
}
enc.wrap.AddBool(key, value)
}
func (enc partialEncoder) AddComplex128(key string, value complex128) {
if _, ok := enc.ignore[key]; ok {
return
}
enc.wrap.AddComplex128(key, value)
}
func (enc partialEncoder) AddComplex64(key string, value complex64) {
if _, ok := enc.ignore[key]; ok {
return
}
enc.wrap.AddComplex64(key, value)
}
func (enc partialEncoder) AddDuration(key string, value time.Duration) {
if _, ok := enc.ignore[key]; ok {
return
}
enc.wrap.AddDuration(key, value)
}
func (enc partialEncoder) AddFloat64(key string, value float64) {
if _, ok := enc.ignore[key]; ok {
return
}
enc.wrap.AddFloat64(key, value)
}
func (enc partialEncoder) AddFloat32(key string, value float32) {
if _, ok := enc.ignore[key]; ok {
return
}
enc.wrap.AddFloat32(key, value)
}
func (enc partialEncoder) AddInt(key string, value int) {
if _, ok := enc.ignore[key]; ok {
return
}
enc.wrap.AddInt(key, value)
}
func (enc partialEncoder) AddInt64(key string, value int64) {
if _, ok := enc.ignore[key]; ok {
return
}
enc.wrap.AddInt64(key, value)
}
func (enc partialEncoder) AddInt32(key string, value int32) {
if _, ok := enc.ignore[key]; ok {
return
}
enc.wrap.AddInt32(key, value)
}
func (enc partialEncoder) AddInt16(key string, value int16) {
if _, ok := enc.ignore[key]; ok {
return
}
enc.wrap.AddInt16(key, value)
}
func (enc partialEncoder) AddInt8(key string, value int8) {
if _, ok := enc.ignore[key]; ok {
return
}
enc.wrap.AddInt8(key, value)
}
func (enc partialEncoder) AddString(key, value string) {
if _, ok := enc.ignore[key]; ok {
return
}
enc.wrap.AddString(key, value)
}
func (enc partialEncoder) AddTime(key string, value time.Time) {
if _, ok := enc.ignore[key]; ok {
return
}
enc.wrap.AddTime(key, value)
}
func (enc partialEncoder) AddUint(key string, value uint) {
if _, ok := enc.ignore[key]; ok {
return
}
enc.wrap.AddUint(key, value)
}
func (enc partialEncoder) AddUint64(key string, value uint64) {
if _, ok := enc.ignore[key]; ok {
return
}
enc.wrap.AddUint64(key, value)
}
func (enc partialEncoder) AddUint32(key string, value uint32) {
if _, ok := enc.ignore[key]; ok {
return
}
enc.wrap.AddUint32(key, value)
}
func (enc partialEncoder) AddUint16(key string, value uint16) {
if _, ok := enc.ignore[key]; ok {
return
}
enc.wrap.AddUint16(key, value)
}
func (enc partialEncoder) AddUint8(key string, value uint8) {
if _, ok := enc.ignore[key]; ok {
return
}
enc.wrap.AddUint8(key, value)
}
func (enc partialEncoder) AddUintptr(key string, value uintptr) {
if _, ok := enc.ignore[key]; ok {
return
}
enc.wrap.AddUintptr(key, value)
}
func (enc partialEncoder) AddReflected(key string, value interface{}) error {
if _, ok := enc.ignore[key]; ok {
return nil
}
return enc.wrap.AddReflected(key, value)
}
func (enc partialEncoder) OpenNamespace(key string) {
if _, ok := enc.ignore[key]; ok {
return
}
enc.wrap.OpenNamespace(key)
}
func (enc partialEncoder) Clone() zapcore.Encoder {
return partialEncoder{
wrap: enc.wrap.Clone(),
ignore: maps.Clone(enc.ignore),
}
}
func (enc partialEncoder) EncodeEntry(entry zapcore.Entry, fields []zapcore.Field) (*buffer.Buffer, error) {
return enc.wrap.EncodeEntry(entry, fields)
}

View file

@ -0,0 +1,63 @@
package zapjournald
import (
"testing"
"github.com/ssgreg/journald"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
func BenchmarkEncoder(b *testing.B) {
zc := zap.NewProductionConfig()
zc.EncoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
zc.Level = zap.NewAtomicLevelAt(zap.InfoLevel)
b.Run("console", func(b *testing.B) {
encoder := zapcore.NewConsoleEncoder(zc.EncoderConfig)
core := NewCore(zc.Level, encoder, &journald.Journal{}, SyslogFields)
core.j.TestModeEnabled = true // Disable actual writing to the journal.
coreWithContext := core.With([]zapcore.Field{
SyslogFacility(LogDaemon),
SyslogIdentifier(),
SyslogPid(),
})
l := zap.New(coreWithContext)
benchmarkEncoder(b, l)
})
b.Run("partial", func(b *testing.B) {
encoder := NewPartialEncoder(zapcore.NewConsoleEncoder(zc.EncoderConfig), SyslogFields)
core := NewCore(zc.Level, encoder, &journald.Journal{}, SyslogFields)
core.j.TestModeEnabled = true // Disable actual writing to the journal.
coreWithContext := core.With([]zapcore.Field{
SyslogFacility(LogDaemon),
SyslogIdentifier(),
SyslogPid(),
})
l := zap.New(coreWithContext)
benchmarkEncoder(b, l)
})
}
func benchmarkEncoder(b *testing.B, l *zap.Logger) {
b.Run("no fields", func(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
l.Info("Simple log message")
}
})
b.Run("application fields", func(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
l.Info("Simple log message", zap.Uint32("count", 123), zap.String("details", "nothing"))
}
})
b.Run("journald fields", func(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
l.Info("Simple log message", SyslogIdentifier())
}
})
}

77
syslog.go Normal file
View file

@ -0,0 +1,77 @@
package zapjournald
import (
"os"
"path/filepath"
"time"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
// Facility defines syslog facility from /usr/include/sys/syslog.h .
type Facility uint32
// Syslog compatibility fields.
const (
SyslogFacilityField = "SYSLOG_FACILITY"
SyslogIdentifierField = "SYSLOG_IDENTIFIER"
SyslogPidField = "SYSLOG_PID"
SyslogTimestampField = "SYSLOG_TIMESTAMP"
)
// Facilities before LogFtp are the same on Linux, BSD, and OS X.
const (
LogKern Facility = iota << 3
LogUser
LogMail
LogDaemon
LogAuth
LogSyslog
LogLpr
LogNews
LogUucp
LogCron
LogAuthpriv
LogFtp
_ // unused
LogAudit // unused
_ // unused
_ // unused
LogLocal0
LogLocal1
LogLocal2
LogLocal3
LogLocal4
LogLocal5
LogLocal6
LogLocal7
)
// LogFacmask is used to extract facility part of the message.
const LogFacmask = 0x03f8
// SyslogFields contains slice of fields that are
// indexed by syslog by default.
var SyslogFields = []string{
SyslogFacilityField,
SyslogIdentifierField,
SyslogPidField,
SyslogTimestampField,
}
func SyslogFacility(facility Facility) zapcore.Field {
return zap.Uint32(SyslogFacilityField, uint32(facility&LogFacmask)>>3)
}
func SyslogIdentifier() zapcore.Field {
return zap.String(SyslogIdentifierField, filepath.Base(os.Args[0]))
}
func SyslogPid() zapcore.Field {
return zap.Int(SyslogPidField, os.Getpid())
}
func SyslogTimestamp(time time.Time) zapcore.Field {
return zap.Time(SyslogTimestampField, time)
}

193
zapjournald.go Normal file
View file

@ -0,0 +1,193 @@
package zapjournald
import (
"fmt"
"math"
"strconv"
"time"
"github.com/ssgreg/journald"
"go.uber.org/zap/zapcore"
"golang.org/x/exp/maps"
)
// Core for zapjournald.
//
// Implements zapcore.LevelEnabler and zapcore.Core interfaces.
type Core struct {
zapcore.LevelEnabler
encoder zapcore.Encoder
j *journald.Journal
// field names, which will be stored in journald structure
storedFieldNames map[string]struct{}
// journald fields, which are always present in current core context
contextStructuredFields map[string]interface{}
}
func NewCore(enab zapcore.LevelEnabler, encoder zapcore.Encoder, journal *journald.Journal, journalFields []string) *Core {
journalFieldsMap := make(map[string]struct{})
for _, field := range journalFields {
journalFieldsMap[field] = struct{}{}
}
return &Core{
LevelEnabler: enab,
encoder: encoder,
j: journal,
storedFieldNames: journalFieldsMap,
contextStructuredFields: make(map[string]interface{}),
}
}
// With adds structured context to the Core.
func (core *Core) With(fields []zapcore.Field) zapcore.Core {
clone := core.clone()
for _, field := range fields {
field.AddTo(clone.encoder)
clone.contextStructuredFields[field.Key] = getFieldValue(field)
}
return clone
}
// Check determines whether the supplied Entry should be logged (using the
// embedded LevelEnabler and possibly some extra logic). If the entry
// should be logged, the Core adds itself to the CheckedEntry and returns
// the result.
//
// Callers must use Check before calling Write.
func (core *Core) Check(entry zapcore.Entry, checked *zapcore.CheckedEntry) *zapcore.CheckedEntry {
if core.Enabled(entry.Level) {
return checked.AddCore(entry, core)
}
return checked
}
// Write serializes the Entry and any Fields supplied at the log site and
// writes them to their destination.
//
// If called, Write should always log the Entry and Fields; it should not
// replicate the logic of Check.
func (core *Core) Write(entry zapcore.Entry, fields []zapcore.Field) error {
prio, err := zapLevelToJournald(entry.Level)
if err != nil {
return err
}
b := pool.Get()
defer b.Free()
writeField(b, "PRIORITY", strconv.Itoa(int(prio)))
if len(core.contextStructuredFields) != 0 {
for k, v := range core.contextStructuredFields {
encodeJournaldField(b, k, v)
}
for _, field := range fields {
if _, isJournalField := core.storedFieldNames[field.Key]; isJournalField {
encodeJournaldField(b, field.Key, getFieldValue(field))
}
}
}
// Generate the message.
buffer, err := core.encoder.EncodeEntry(entry, fields)
if err != nil {
return fmt.Errorf("failed to encode log entry: %w", err)
}
defer buffer.Free()
writeFieldBytes(b, "MESSAGE", buffer.Bytes())
// Write the message.
return core.j.WriteMsg(b.Bytes())
}
// Sync flushes buffered logs (not used).
func (core *Core) Sync() error {
return nil
}
// clone returns clone of core.
func (core *Core) clone() *Core {
return &Core{
LevelEnabler: core.LevelEnabler,
encoder: core.encoder.Clone(),
j: core.j,
storedFieldNames: maps.Clone(core.storedFieldNames),
contextStructuredFields: maps.Clone(core.contextStructuredFields),
}
}
// getFieldValue returns underlying value stored in zapcore.Field.
func getFieldValue(f zapcore.Field) interface{} {
switch f.Type {
case zapcore.ArrayMarshalerType,
zapcore.ObjectMarshalerType,
zapcore.InlineMarshalerType,
zapcore.BinaryType,
zapcore.ByteStringType,
zapcore.Complex128Type,
zapcore.Complex64Type,
zapcore.TimeFullType,
zapcore.ReflectType,
zapcore.NamespaceType,
zapcore.StringerType,
zapcore.ErrorType,
zapcore.SkipType:
return f.Interface
case zapcore.DurationType:
return time.Duration(f.Integer).String()
case zapcore.Float64Type:
// See https://github.com/uber-go/zap/blob/v1.26.0/buffer/buffer.go#L79
f := math.Float64frombits(uint64(f.Integer))
return strconv.FormatFloat(f, 'f', -1, 64)
case zapcore.Float32Type:
f := math.Float32frombits(uint32(f.Integer))
return strconv.FormatFloat(float64(f), 'f', -1, 32)
case zapcore.Int64Type,
zapcore.Int32Type,
zapcore.Int16Type,
zapcore.Int8Type:
return strconv.FormatInt(f.Integer, 10)
case
zapcore.Uint64Type,
zapcore.Uint32Type,
zapcore.Uint16Type,
zapcore.Uint8Type,
zapcore.UintptrType:
return strconv.FormatUint(uint64(f.Integer), 10)
case zapcore.BoolType:
return strconv.FormatBool(f.Integer == 1)
case zapcore.StringType:
return f.String
case zapcore.TimeType:
if f.Interface != nil {
// for example: zap.Time("k", time.Unix(100900, 0).In(time.UTC)) - will produce: "100900000000000 UTC" (result in nanoseconds)
return fmt.Sprintf("%d %v", f.Integer, f.Interface)
}
return strconv.FormatUint(uint64(f.Integer), 10)
default:
panic(fmt.Sprintf("unknown field type: %v", f))
}
}
func zapLevelToJournald(l zapcore.Level) (journald.Priority, error) {
switch l {
case zapcore.DebugLevel:
return journald.PriorityDebug, nil
case zapcore.InfoLevel:
return journald.PriorityInfo, nil
case zapcore.WarnLevel:
return journald.PriorityWarning, nil
case zapcore.ErrorLevel:
return journald.PriorityErr, nil
case zapcore.DPanicLevel:
return journald.PriorityCrit, nil
case zapcore.PanicLevel:
return journald.PriorityCrit, nil
case zapcore.FatalLevel:
return journald.PriorityCrit, nil
default:
return 0, fmt.Errorf("unknown log level: %v", l)
}
}

94
zapjournald_test.go Normal file
View file

@ -0,0 +1,94 @@
package zapjournald
import (
"fmt"
"net"
"testing"
"time"
"github.com/stretchr/testify/assert"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
// TestGetFieldValueWithStringFormatting testing unexported function getFieldValue and verifying that all zap field types have correct return values.
func TestGetFieldValueWithStringFormatting(t *testing.T) {
// Interface types.
addr := net.ParseIP("1.2.3.4")
name := usernameTestExample("phil")
ints := []int{5, 6}
tests := []struct {
name string
field zap.Field
expect interface{}
}{
{"ObjectMarshaler", zap.Object("k", name), "phil"},
{"ArrayMarshaler", zap.Array("k", boolsTestExample([]bool{true})), "[true]"},
{"Binary", zap.Binary("k", []byte("ab12")), "ab12"},
{"Bool", zap.Bool("k", true), "1"},
{"ByteString", zap.ByteString("k", []byte("ab12")), "ab12"},
{"Complex128", zap.Complex128("k", 1+2i), "(1+2i)"},
{"Complex64", zap.Complex64("k", 1+2i), "(1+2i)"},
{"Duration", zap.Duration("k", 1), "1"},
{"Float64", zap.Float64("k", 3.14), "4614253070214989087"},
{"Float32", zap.Float32("k", 3.14), "1078523331"},
{"Int64", zap.Int64("k", 1), "1"},
{"Int32", zap.Int32("k", 1), "1"},
{"Int16", zap.Int16("k", 1), "1"},
{"Int8", zap.Int8("k", 1), "1"},
{"String", zap.String("k", "foo"), "foo"},
{"Time", zap.Time("k", time.Unix(0, 0).In(time.UTC)), "0 UTC"},
{"TimeFull", zap.Time("k", time.Time{}), "0001-01-01 00:00:00 +0000 UTC"},
{"Uint", zap.Uint("k", 1), "1"},
{"Uint64", zap.Uint64("k", 1), "1"},
{"Uint32", zap.Uint32("k", 1), "1"},
{"Uint16", zap.Uint16("k", 1), "1"},
{"Uint8", zap.Uint8("k", 1), "1"},
{"Uintptr", zap.Uintptr("k", 0xa), "10"},
{"Namespace", zap.Namespace("k"), "<nil>"},
{"Stringer", zap.Stringer("k", addr), "1.2.3.4"},
{"Reflect", zap.Reflect("k", ints), "[5 6]"},
{"Error", zap.Error(fmt.Errorf("test")), "test"},
{"Skip", zap.Skip(), "<nil>"},
{"InlineMarshaller", zap.Inline(name), "phil"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
fieldValue := valueToString(getFieldValue(tt.field))
if !assert.Equal(t, tt.expect, fieldValue, "Unexpected output %s.", tt.name) {
t.Logf("type expected: %T\nGot: %T", tt.expect, fieldValue)
}
})
}
}
// usernameTestExample type, which are implements ObjectMarshaller interface.
type usernameTestExample string
func (n usernameTestExample) MarshalLogObject(enc zapcore.ObjectEncoder) error {
enc.AddString("username", string(n))
return nil
}
// boolsTestExample type, which are implements ArrayMarshaller interface.
type boolsTestExample []bool
func (bs boolsTestExample) MarshalLogArray(arr zapcore.ArrayEncoder) error {
for i := range bs {
arr.AppendBool(bs[i])
}
return nil
}
func valueToString(value interface{}) string {
switch rv := value.(type) {
case string:
return rv
case []byte:
return string(rv)
default:
return fmt.Sprint(value)
}
}