Browse Source

new scribe to output to systemd/journal on Linux

Signed-off-by: Alexander Diemand <codieplusplus@apax.net>
master^2
Alexander Diemand 3 years ago
parent
commit
aeb14f2f90
No known key found for this signature in database
GPG Key ID: 99283F5327C5D38F
  1. 1
      cabal.project
  2. 5
      examples/CHANGELOG.md
  3. 3
      examples/lobemo-examples.cabal
  4. 20
      examples/simple/Main.lhs
  5. 19
      iohk-monitoring/iohk-monitoring.cabal
  6. 116
      iohk-monitoring/src/Cardano/BM/Backend/Log.lhs
  7. 5
      iohk-monitoring/src/Cardano/BM/Configuration/Model.lhs
  8. 4
      iohk-monitoring/src/Cardano/BM/Data/Output.lhs
  9. 1
      nix/.stack.nix/default.nix
  10. 18
      nix/.stack.nix/iohk-monitoring.nix
  11. 1
      nix/.stack.nix/lobemo-examples.nix
  12. 36
      nix/.stack.nix/lobemo-scribe-systemd.nix
  13. 3
      nix/pkgs.nix
  14. 202
      plugins/scribe-systemd/LICENSE
  15. 5
      plugins/scribe-systemd/NOTICE
  16. 2
      plugins/scribe-systemd/README.md
  17. 2
      plugins/scribe-systemd/Setup.hs
  18. 40
      plugins/scribe-systemd/lobemo-scribe-systemd.cabal
  19. 146
      plugins/scribe-systemd/src/Cardano/BM/Scribe/Systemd.lhs
  20. 1
      stack.yaml

1
cabal.project

@ -9,6 +9,7 @@ packages:
plugins/backend-graylog
plugins/backend-monitoring
plugins/backend-prometheus
plugins/scribe-systemd
examples
package iohk-monitoring

5
examples/CHANGELOG.md

@ -1,5 +0,0 @@
# Revision history for lobemo-examples
## 0.1.0.0 -- YYYY-mm-dd
* First version. Released on an unsuspecting world.

3
examples/lobemo-examples.cabal

@ -12,7 +12,7 @@ maintainer: operations@iohk.io
copyright: 2019 IOHK
category: Benchmarking
build-type: Simple
extra-source-files: CHANGELOG.md
extra-source-files:
executable example-simple
main-is: Main.lhs
@ -27,6 +27,7 @@ executable example-simple
aeson,
iohk-monitoring,
lobemo-backend-editor,
lobemo-scribe-systemd,
async,
bytestring,
mtl

20
examples/simple/Main.lhs

@ -16,14 +16,17 @@ import Control.Concurrent (threadDelay)
import Control.Concurrent.MVar (MVar, newMVar, modifyMVar_, withMVar)
import Data.Aeson (FromJSON)
-- import Cardano.BM.Backend.Editor (plugin)
import Cardano.BM.Backend.Switchboard (addUserDefinedBackend)
import Cardano.BM.Data.Backend
import qualified Cardano.BM.Configuration.Model as CM
import Cardano.BM.Configuration.Static (defaultConfigStdout)
#ifdef LINUX
import Cardano.BM.Scribe.Systemd (plugin)
import Cardano.BM.Data.Output (ScribeDefinition (..),
ScribePrivacy (..), ScribeKind (..), ScribeFormat (..))
#endif
import Cardano.BM.Plugin (loadPlugin)
import Cardano.BM.Setup (setupTrace_)
import Cardano.BM.Trace (Trace, appendName, logDebug, logError,
logInfo, logNotice, logWarning)
@ -76,21 +79,22 @@ main = do
, scPrivacy = ScPublic
, scRotation = Nothing
}
, ScribeDefinition {
scName = "systemd"
, scFormat = ScText
, scKind = JournalSK
, scPrivacy = ScPublic
, scRotation = Nothing
}
]
CM.setScribes c "simple.systemd" (Just ["JournalSK::systemd"])
CM.setScribes c "simple.systemd" (Just ["JournalSK"])
#endif
CM.setScribes c "simple.json" (Just ["StdoutSK::json"])
(tr :: Trace IO String, sb) <- setupTrace_ c "simple"
be :: MyBackend String <- realize c
let mybe = MkBackend { bEffectuate = effectuate be, bUnrealize = unrealize be }
addUserDefinedBackend sb mybe "MyBackend"
-- load plugins
-- Cardano.BM.Backend.Editor.plugin c tr sb
-- >>= loadPlugin sb
#ifdef LINUX
Cardano.BM.Scribe.Systemd.plugin c tr sb
>>= loadPlugin sb
#endif
let trText = appendName "text" tr
trJson = appendName "json" tr
#ifdef LINUX

19
iohk-monitoring/iohk-monitoring.cabal

@ -17,16 +17,6 @@ flag disable-observables
default: False
manual: True
flag disable-systemd
description: Turn off systemd journal scribe.
default: False
manual: True
flag disable-examples
description: Turn off building of examples.
default: False
manual: True
flag performance-test-queue
description: Set the huge size for backends' queues.
default: False
@ -90,7 +80,7 @@ library
other-extensions: OverloadedStrings
build-depends: base >= 4.11,
contra-tracer,
aeson >= 1.4.4,
aeson >= 1.4.2,
array,
async,
async-timer,
@ -124,11 +114,6 @@ library
else
build-depends: unix
if os(linux) && !flag(disable-systemd)
cpp-options: -DENABLE_SYSTEMD
build-depends: hsyslog,
libsystemd-journal
if !flag(disable-observables)
cpp-options: -DENABLE_OBSERVABLES
@ -159,7 +144,7 @@ test-suite tests
build-depends: base,
contra-tracer,
iohk-monitoring,
aeson >= 1.4.4,
aeson >= 1.4.2,
array,
async,
bytestring,

116
iohk-monitoring/src/Cardano/BM/Backend/Log.lhs

@ -24,6 +24,7 @@ module Cardano.BM.Backend.Log
, realize
, unrealize
, registerScribe
, sev2klog
-- * re-exports
, K.Scribe
) where
@ -59,26 +60,11 @@ import System.Directory (createDirectoryIfMissing)
import System.FilePath (takeDirectory)
import System.IO (BufferMode (LineBuffering), Handle, hClose,
hSetBuffering, stderr, stdout, openFile, IOMode (WriteMode))
#ifdef ENABLE_SYSTEMD
import Data.Aeson (encode)
import qualified Data.ByteString.Lazy as BL (toStrict)
import qualified Data.Text.Encoding as T (encodeUtf8)
import Language.Haskell.TH.Syntax (Loc(Loc, loc_filename, loc_start))
import Systemd.Journal (JournalFields, codeFile, codeLine, message,
mkJournalField, priority, sendJournalFields,
syslogFacility, syslogIdentifier)
import qualified Systemd.Journal as J
import System.Posix.Syslog (Facility)
#endif
import Paths_iohk_monitoring (version)
import qualified Katip as K
import qualified Katip.Core as KC
import Katip.Scribes.Handle (brackets)
#ifdef ENABLE_SYSTEMD
import Katip.Format.Time (formatAsIso8601)
#endif
import qualified Cardano.BM.Configuration as Config
import Cardano.BM.Configuration.Model (getScribes, getSetupScribes)
@ -209,10 +195,19 @@ instance (ToJSON a, FromJSON a) => IsBackend Log a where
\subsubsection{Create and register \emph{katip} scribes}
\begin{code}
registerScribe :: Log a -> K.Scribe -> ScribeId -> IO ()
registerScribe = undefined
\end{code}
registerScribe katip scr name =
modifyMVar_ (getK katip) $ \k -> do
newenv <- K.registerScribe name scr scribeSettings (kLogEnv k)
return $ k { kLogEnv = newenv }
scribeSettings :: KC.ScribeSettings
scribeSettings =
let bufferSize = 5000 -- size of the queue (in log items)
in
KC.ScribeSettings bufferSize
\begin{code}
registerScribes :: [ScribeDefinition] -> K.LogEnv -> IO K.LogEnv
registerScribes [] le = return le
registerScribes (defsc : dscs) le = do
@ -224,11 +219,6 @@ registerScribes (defsc : dscs) le = do
scr <- createScribe kind sctype name rotParams
registerScribes dscs =<< K.registerScribe name' scr scribeSettings le
where
scribeSettings :: KC.ScribeSettings
scribeSettings =
let bufferSize = 5000 -- size of the queue (in log items)
in
KC.ScribeSettings bufferSize
createScribe FileSK ScText name rotParams = mkTextFileScribe
rotParams
(FileDescription $ unpack name)
@ -237,9 +227,7 @@ registerScribes (defsc : dscs) le = do
rotParams
(FileDescription $ unpack name)
False
#if defined(ENABLE_SYSTEMD)
createScribe JournalSK _ _ _ = mkJournalScribe
#endif
-- createScribe JournalSK _ _ _ = mkJournalScribe
createScribe StdoutSK sctype _ _ = mkStdoutScribe sctype
createScribe StderrSK sctype _ _ = mkStderrScribe sctype
createScribe DevNullSK _ _ _ = mkDevNullScribe
@ -293,7 +281,7 @@ passN :: ToJSON a => ScribeId -> Log a -> LogObject a -> IO ()
passN backend katip (LogObject loname lometa loitem) = do
env <- kLogEnv <$> readMVar (getK katip)
forM_ (Map.toList $ K._logEnvScribes env) $
\(scName, (KC.ScribeHandle _ shChan)) ->
\(scName, (KC.ScribeHandle _ shChan)) -> do
-- check start of name to match |ScribeKind|
if backend `isPrefixOf` scName
then do
@ -588,77 +576,3 @@ prefixPath :: FileDescription -> FilePath
prefixPath = takeDirectory . filePath
\end{code}
\begin{code}
#ifdef ENABLE_SYSTEMD
mkJournalScribe :: IO K.Scribe
mkJournalScribe = return $ journalScribe Nothing (sev2klog Debug) K.V3
-- taken from https://github.com/haskell-service/katip-libsystemd-journal
journalScribe :: Maybe Facility
-> K.Severity
-> K.Verbosity
-> K.Scribe
journalScribe facility severity verbosity = K.Scribe liPush scribeFinalizer
where
liPush :: K.LogItem a => K.Item a -> IO ()
liPush i = when (K.permitItem severity i) $
sendJournalFields $ itemToJournalFields facility verbosity i
scribeFinalizer :: IO ()
scribeFinalizer = pure ()
\end{code}
Converts a |Katip Item| into a libsystemd-journal |JournalFields| map.
\begin{code}
itemToJournalFields :: K.LogItem a
=> Maybe Facility
-> K.Verbosity
-> K.Item a
-> JournalFields
itemToJournalFields facility verbosity item = mconcat [ defaultFields item
, maybe HM.empty facilityFields facility
, maybe HM.empty locFields (K._itemLoc item)
]
where
defaultFields kItem =
mconcat [ message (TL.toStrict $ toLazyText $ KC.unLogStr (KC._itemMessage kItem))
, priority (mapSeverity (KC._itemSeverity kItem))
, syslogIdentifier (unNS (KC._itemApp kItem))
, HM.fromList [ (environment, T.encodeUtf8 $ KC.getEnvironment (KC._itemEnv kItem))
, (namespace, T.encodeUtf8 $ unNS (KC._itemNamespace kItem))
, (payload, BL.toStrict $ encode $ KC.payloadObject verbosity (KC._itemPayload kItem))
, (thread, T.encodeUtf8 $ KC.getThreadIdText (KC._itemThread kItem))
, (time, T.encodeUtf8 $ formatAsIso8601 (KC._itemTime kItem))
]
]
facilityFields = syslogFacility
locFields Loc{..} = mconcat [ codeFile loc_filename
, codeLine (fst loc_start)
]
environment = mkJournalField "environment"
namespace = mkJournalField "namespace"
payload = mkJournalField "payload"
thread = mkJournalField "thread"
time = mkJournalField "time"
unNS ns = case K.unNamespace ns of
[] -> T.empty
[p] -> p
parts -> T.intercalate "." parts
mapSeverity s = case s of
K.DebugS -> J.Debug
K.InfoS -> J.Info
K.NoticeS -> J.Notice
K.WarningS -> J.Warning
K.ErrorS -> J.Error
K.CriticalS -> J.Critical
K.AlertS -> J.Alert
K.EmergencyS -> J.Emergency
#endif
\end{code}

5
iohk-monitoring/src/Cardano/BM/Configuration/Model.lhs

@ -481,10 +481,7 @@ setupFromRepresentation r = do
fillRotationParams :: Maybe RotationParameters -> [ScribeDefinition] -> [ScribeDefinition]
fillRotationParams defaultRotation = map $ \sd ->
if (scKind sd /= StdoutSK) && (scKind sd /= StderrSK) && (scKind sd /= DevNullSK)
#ifdef ENABLE_SYSTEMD
&& (scKind sd /= JournalSK)
#endif
if scKind sd == FileSK
then
sd { scRotation = maybe defaultRotation Just (scRotation sd) }
else

4
iohk-monitoring/src/Cardano/BM/Data/Output.lhs

@ -43,9 +43,7 @@ This identifies katip's scribes by type.
data ScribeKind = FileSK
| StdoutSK
| StderrSK
#ifdef ENABLE_SYSTEMD
| JournalSK
#endif
-- | JournalSK
| DevNullSK
| UserDefinedSK
deriving (Generic, Eq, Ord, Show, Read, FromJSON, ToJSON)

1
nix/.stack.nix/default.nix generated

@ -15,6 +15,7 @@
lobemo-backend-graylog = ./lobemo-backend-graylog.nix;
lobemo-backend-monitoring = ./lobemo-backend-monitoring.nix;
lobemo-backend-prometheus = ./lobemo-backend-prometheus.nix;
lobemo-scribe-systemd = ./lobemo-scribe-systemd.nix;
lobemo-examples = ./lobemo-examples.nix;
ekg-prometheus-adapter = ./ekg-prometheus-adapter.nix;
};

18
nix/.stack.nix/iohk-monitoring.nix generated

@ -1,11 +1,6 @@
{ system, compiler, flags, pkgs, hsPkgs, pkgconfPkgs, ... }:
{
flags = {
disable-observables = false;
disable-systemd = false;
disable-examples = false;
performance-test-queue = false;
};
flags = { disable-observables = false; performance-test-queue = false; };
package = {
specVersion = "1.10";
identifier = { name = "iohk-monitoring"; version = "0.1.10.1"; };
@ -21,7 +16,7 @@
};
components = {
"library" = {
depends = ([
depends = [
(hsPkgs.base)
(hsPkgs.contra-tracer)
(hsPkgs.aeson)
@ -55,12 +50,7 @@
(hsPkgs.libyaml)
] ++ (if system.isWindows
then [ (hsPkgs.Win32) ]
else [
(hsPkgs.unix)
])) ++ (pkgs.lib).optionals (system.isLinux && !flags.disable-systemd) [
(hsPkgs.hsyslog)
(hsPkgs.libsystemd-journal)
];
else [ (hsPkgs.unix) ]);
};
tests = {
"tests" = {
@ -100,4 +90,4 @@
};
};
};
} // rec { src = (pkgs.lib).mkDefault ../.././iohk-monitoring; }
} // rec { src = (pkgs.lib).mkDefault ../.././iohk-monitoring; }

1
nix/.stack.nix/lobemo-examples.nix generated

@ -23,6 +23,7 @@
(hsPkgs.aeson)
(hsPkgs.iohk-monitoring)
(hsPkgs.lobemo-backend-editor)
(hsPkgs.lobemo-scribe-systemd)
(hsPkgs.async)
(hsPkgs.bytestring)
(hsPkgs.mtl)

36
nix/.stack.nix/lobemo-scribe-systemd.nix generated

@ -0,0 +1,36 @@
{ system, compiler, flags, pkgs, hsPkgs, pkgconfPkgs, ... }:
{
flags = {};
package = {
specVersion = "2.0";
identifier = { name = "lobemo-scribe-systemd"; version = "0.1.0.0"; };
license = "Apache-2.0";
copyright = "2019 IOHK";
maintainer = "operations@iohk.io";
author = "Alexander Diemand";
homepage = "https://github.com/input-output-hk/iohk-monitoring-framework";
url = "";
synopsis = "provides a backend for logging to systemd/journal";
description = "";
buildType = "Simple";
};
components = {
"library" = {
depends = ([
(hsPkgs.base)
(hsPkgs.iohk-monitoring)
(hsPkgs.aeson)
(hsPkgs.bytestring)
(hsPkgs.katip)
(hsPkgs.text)
(hsPkgs.template-haskell)
(hsPkgs.unordered-containers)
] ++ (if system.isWindows
then [ (hsPkgs.Win32) ]
else [ (hsPkgs.unix) ])) ++ (pkgs.lib).optionals (system.isLinux) [
(hsPkgs.hsyslog)
(hsPkgs.libsystemd-journal)
];
};
};
} // rec { src = (pkgs.lib).mkDefault ../.././plugins/scribe-systemd; }

3
nix/pkgs.nix

@ -43,9 +43,6 @@ let
# Add a variant of iohk-monitoring to test disabling of flags
packages.iohk-monitoring-minimal.flags = {
disable-observables = true;
disable-systemd = true;
# Keep examples, to see if they build
disable-examples = false;
};
}
];

202
plugins/scribe-systemd/LICENSE

@ -0,0 +1,202 @@
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.

5
plugins/scribe-systemd/NOTICE

@ -0,0 +1,5 @@
Copyright 2019 IOHK
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.txt
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.

2
plugins/scribe-systemd/README.md

@ -0,0 +1,2 @@
# backend for systemd/journal logging

2
plugins/scribe-systemd/Setup.hs

@ -0,0 +1,2 @@
import Distribution.Simple
main = defaultMain

40
plugins/scribe-systemd/lobemo-scribe-systemd.cabal

@ -0,0 +1,40 @@
cabal-version: 2.0
name: lobemo-scribe-systemd
version: 0.1.0.0
synopsis: provides a backend for logging to systemd/journal
-- description:
homepage: https://github.com/input-output-hk/iohk-monitoring-framework
-- bug-reports:
license: Apache-2.0
license-files: LICENSE, NOTICE
author: Alexander Diemand
maintainer: operations@iohk.io
copyright: 2019 IOHK
category: Benchmarking
build-type: Simple
extra-source-files: README.md
library
exposed-modules: Cardano.BM.Scribe.Systemd
-- other-modules:
-- other-extensions:
default-extensions: OverloadedStrings
build-depends: base >=4.11,
iohk-monitoring,
aeson,
bytestring,
katip,
text,
template-haskell,
unordered-containers
if os(windows)
build-depends: Win32
else
build-depends: unix
if os(linux)
build-depends: hsyslog,
libsystemd-journal
hs-source-dirs: src
default-language: Haskell2010

146
plugins/scribe-systemd/src/Cardano/BM/Scribe/Systemd.lhs

@ -0,0 +1,146 @@
\subsection{Cardano.BM.Scribe.Systemd}
\label{code:Cardano.BM.Scribe.Systemd}
%if style == newcode
\begin{code}
{-# LANGUAGE CPP #-}
{-# LANGUAGE RecordWildCards #-}
#if defined(linux_HOST_OS)
#define LINUX
#endif
module Cardano.BM.Scribe.Systemd
(
#if defined(LINUX)
plugin
#endif
) where
#ifdef LINUX
import Control.Monad (when)
import Data.Aeson (ToJSON, FromJSON, encode)
import qualified Data.ByteString.Lazy as BL (toStrict)
import qualified Data.HashMap.Strict as HM
import qualified Data.Text as T
import qualified Data.Text.Encoding as T (encodeUtf8)
import qualified Data.Text.Lazy as TL
import Data.Text.Lazy.Builder (toLazyText)
import Language.Haskell.TH.Syntax (Loc(Loc, loc_filename, loc_start))
import Systemd.Journal (JournalFields, codeFile, codeLine, message,
mkJournalField, priority, sendJournalFields,
syslogFacility, syslogIdentifier)
import qualified Systemd.Journal as J
import System.Posix.Syslog (Facility)
import qualified Katip as K
import qualified Katip.Core as KC
import Katip.Format.Time (formatAsIso8601)
import Katip.Scribes.Handle (brackets)
import Cardano.BM.Configuration
import Cardano.BM.Backend.Log (sev2klog)
import Cardano.BM.Data.Backend
import Cardano.BM.Data.LogItem
import Cardano.BM.Data.Output (ScribeId)
import Cardano.BM.Data.Severity
import Cardano.BM.Data.Trace
import Cardano.BM.Plugin (Plugin (..))
#endif
\end{code}
%endif
This plugin provides a scribe to \emph{katip} to output logged items
to systemd's journal on \emph{Linux}.
\subsubsection{Plugin definition}
\begin{code}
#ifdef LINUX
plugin :: (IsEffectuator s a, ToJSON a, FromJSON a)
=> Configuration -> Trace IO a -> s a -> IO (Plugin a)
plugin config trace sb =
ScribePlugin
<$> mkJournalScribe
<*> pure "JournalSK"
#endif
\end{code}
\subsubsection{Scribe definition}
\begin{code}
#ifdef LINUX
mkJournalScribe :: IO K.Scribe
mkJournalScribe = return $ journalScribe Nothing (sev2klog Debug) K.V3
-- taken from https://github.com/haskell-service/katip-libsystemd-journal
journalScribe :: Maybe Facility
-> K.Severity
-> K.Verbosity
-> K.Scribe
journalScribe facility severity verbosity = K.Scribe liPush scribeFinalizer
where
liPush :: K.LogItem a => K.Item a -> IO ()
liPush i = when (K.permitItem severity i) $
sendJournalFields $ itemToJournalFields facility verbosity i
scribeFinalizer :: IO ()
scribeFinalizer = pure ()
#endif
\end{code}
\subsubsection{Conversion utilities}
Converts a |Katip Item| into a libsystemd-journal |JournalFields| map.
\begin{code}
#ifdef LINUX
itemToJournalFields :: K.LogItem a
=> Maybe Facility
-> K.Verbosity
-> K.Item a
-> JournalFields
itemToJournalFields facility verbosity item = mconcat [ defaultFields item
, maybe HM.empty facilityFields facility
, maybe HM.empty locFields (K._itemLoc item)
]
where
defaultFields kItem =
mconcat [ message (TL.toStrict $ toLazyText $ KC.unLogStr (KC._itemMessage kItem))
, priority (mapSeverity (KC._itemSeverity kItem))
, syslogIdentifier (unNS (KC._itemApp kItem))
, HM.fromList [ (environment, T.encodeUtf8 $ KC.getEnvironment (KC._itemEnv kItem))
, (namespace, T.encodeUtf8 $ unNS (KC._itemNamespace kItem))
, (payload, BL.toStrict $ encode $ KC.payloadObject verbosity (KC._itemPayload kItem))
, (thread, T.encodeUtf8 $ KC.getThreadIdText (KC._itemThread kItem))
, (time, T.encodeUtf8 $ formatAsIso8601 (KC._itemTime kItem))
]
]
facilityFields = syslogFacility
locFields Loc{..} = mconcat [ codeFile loc_filename
, codeLine (fst loc_start)
]
environment = mkJournalField "environment"
namespace = mkJournalField "namespace"
payload = mkJournalField "payload"
thread = mkJournalField "thread"
time = mkJournalField "time"
unNS ns = case K.unNamespace ns of
[] -> T.empty
[p] -> p
parts -> T.intercalate "." parts
mapSeverity s = case s of
K.DebugS -> J.Debug
K.InfoS -> J.Info
K.NoticeS -> J.Notice
K.WarningS -> J.Warning
K.ErrorS -> J.Error
K.CriticalS -> J.Critical
K.AlertS -> J.Alert
K.EmergencyS -> J.Emergency
#endif
\end{code}

1
stack.yaml

@ -10,6 +10,7 @@ packages:
- plugins/backend-graylog
- plugins/backend-monitoring
- plugins/backend-prometheus
- plugins/scribe-systemd
- examples
extra-deps:

Loading…
Cancel
Save