@@ -3,19 +3,17 @@ module Katip.Scribes.Handle where
33-------------------------------------------------------------------------------
44import Control.Applicative as A
55import Control.Concurrent
6−import Control.Exception (finally)
6+import Control.Exception (bracket_, finally)
77import Data.Aeson
8−import Data.Aeson.Text
9−import Data.ByteString.Builder as B
10−import Data.ByteString.Lazy as BL (hPutStr)
8+import Data.Text.Lazy (toStrict)
9+import Data.Text.Lazy.Encoding (decodeUtf8)
10+import qualified Data.HashMap.Strict as HM
1111import Data.Monoid as M
1212import Data.Scientific as S
1313import Data.Text (Text)
14−import Data.Text.Lazy.Builder as TL
15−import Data.Text.Lazy.Encoding (encodeUtf8)
14+import Data.Text.Lazy.Builder
15+import Data.Text.Lazy.IO as T
1616import System.IO
17−import qualified Data.HashMap.Strict as HM
18−
1917-------------------------------------------------------------------------------
2018import Katip.Core
2119import Katip.Format.Time (formatAsLogTime)
@@ -23,20 +21,15 @@ import Katip.Format.Time (formatAsLogTime)
2321
2422
2523-------------------------------------------------------------------------------
26−brackets :: TL.Builder -> TL.Builder
24+brackets :: Builder -> Builder
2725brackets m = fromText "[" M.<> m <> fromText "]"
2826
29−textBuilderToBS :: TL.Builder -> B.Builder
30−textBuilderToBS = B.lazyByteString . encodeUtf8 . toLazyText
31−
32−appendNL :: TL.Builder -> TL.Builder
33−appendNL b = b <> TL.singleton '\n'
3427
3528-------------------------------------------------------------------------------
36−getKeys :: LogItem s => Verbosity -> s -> [TL.Builder]
29+getKeys :: LogItem s => Verbosity -> s -> [Builder]
3730getKeys verb a = concat (renderPair A.<$> HM.toList (payloadObject verb a))
3831 where
39− renderPair :: (Text, Value) -> [TL.Builder]
32+ renderPair :: (Text, Value) -> [Builder]
4033 renderPair (k,v) =
4134 case v of
4235 Object o -> concat [renderPair (k <> "." <> k', v') | (k', v') <- HM.toList o]
@@ -72,19 +65,6 @@ data ColorStrategy
7265mkHandleScribe :: ColorStrategy -> Handle -> PermitFunc -> Verbosity -> IO Scribe
7366mkHandleScribe = mkHandleScribeWithFormatter bracketFormat
7467
75−
76−mkFileScribeWithFormatter :: (forall a . LogItem a => ItemFormatter a)
77− -> ColorStrategy
78− -> FilePath
79− -> PermitFunc
80− -> Verbosity
81− -> IO Scribe
82−mkFileScribeWithFormatter formatter color f permitF verb = do
83− h <- openBinaryFile f AppendMode
84− Scribe logger finalizer permit <- mkHandleScribeWithFormatter formatter color h permitF verb
85− return (Scribe logger (finalizer `finally` hClose h) permit)
86−
87−
8868-- | Logs to a file handle such as stdout, stderr, or a file. Takes a custom
8969-- `ItemFormatter` that can be used to format `Item` as needed.
9070--
@@ -97,12 +77,14 @@ mkHandleScribeWithFormatter :: (forall a . LogItem a => ItemFormatter a)
9777 -> Verbosity
9878 -> IO Scribe
9979mkHandleScribeWithFormatter itemFormatter cs h permitF verb = do
80+ hSetBuffering h LineBuffering
10081 colorize <- case cs of
10182 ColorIfTerminal -> hIsTerminalDevice h
10283 ColorLog b -> return b
10384 lock <- newMVar ()
104− let logger i@Item{..} = withMVar lock $ \() -> do
105− BL.hPutStr h $ toLazyByteString $ itemFormatter colorize verb i
85+ let logger i@Item{..} = do
86+ bracket_ (takeMVar lock) (putMVar lock ()) $
87+ T.hPutStrLn h $ toLazyText $ itemFormatter colorize verb i
10688 return $ Scribe logger (hFlush h) permitF
10789
10890
@@ -113,17 +95,19 @@ mkHandleScribeWithFormatter itemFormatter cs h permitF verb = do
11395-- 'closeScribe'/'closeScribes'. Does not do log coloring. Sets handle
11496-- to 'LineBuffering' mode.
11597mkFileScribe :: FilePath -> PermitFunc -> Verbosity -> IO Scribe
116−mkFileScribe = mkFileScribeWithFormatter bracketFormat (ColorLog False)
98+mkFileScribe f permitF verb = do
99+ h <- openFile f AppendMode
100+ Scribe logger finalizer permit <- mkHandleScribe (ColorLog False) h permitF verb
101+ return (Scribe logger (finalizer `finally` hClose h) permit)
117102
118103
119104-------------------------------------------------------------------------------
120105-- | A custom ItemFormatter for logging `Item`s. Takes a `Bool` indicating
121106-- whether to colorize the output, `Verbosity` of output, and an `Item` to
122−-- format. Note that formatter is responsible for appending the newline at the
123−-- end of the string if required
107+-- format.
124108--
125109-- See `bracketFormat` and `jsonFormat` for examples.
126−type ItemFormatter a = Bool -> Verbosity -> Item a -> B.Builder
110+type ItemFormatter a = Bool -> Verbosity -> Item a -> Builder
127111
128112
129113formatItem :: LogItem a => ItemFormatter a
@@ -137,10 +121,10 @@ formatItem = bracketFormat
137121-- > [2016-05-11 21:01:15][MyApp.confrabulation][Debug][myhost.example.com][PID 1724][ThreadId 1154][confrab_factor:42.0][main:Helpers.Logging Helpers/Logging.hs:41:9] Confrabulating widgets, with extra namespace and context
138122-- > [2016-05-11 21:01:15][MyApp][Info][myhost.example.com][PID 1724][ThreadId 1154][main:Helpers.Logging Helpers/Logging.hs:43:7] Namespace and context are back to normal
139123bracketFormat :: LogItem a => ItemFormatter a
140−bracketFormat withColor verb Item{..} = textBuilderToBS $ appendNL $
124+bracketFormat withColor verb Item{..} =
141125 brackets nowStr <>
142126 brackets (mconcat $ map fromText $ intercalateNs _itemNamespace) <>
143− brackets (renderSeverity' _itemSeverity) <>
127+ brackets (fromText (renderSeverity' _itemSeverity)) <>
144128 brackets (fromString _itemHost) <>
145129 brackets ("PID " <> fromString (show _itemProcess)) <>
146130 brackets ("ThreadId " <> fromText (getThreadIdText _itemThread)) <>
@@ -151,7 +135,7 @@ bracketFormat withColor verb Item{..} = textBuilderToBS $ appendNL $
151135 nowStr = fromText (formatAsLogTime _itemTime)
152136 ks = map brackets $ getKeys verb _itemPayload
153137 renderSeverity' severity =
154− colorBySeverity withColor severity (fromText $ renderSeverity severity)
138+ colorBySeverity withColor severity (renderSeverity severity)
155139
156140-- | Logs items as JSON. This can be useful in circumstances where you already
157141-- have infrastructure that is expecting JSON to be logged to a standard stream
@@ -161,15 +145,15 @@ bracketFormat withColor verb Item{..} = textBuilderToBS $ appendNL $
161145-- > {"at":"2018-10-02T21:50:30.4523848Z","env":"production","ns":["MyApp","confrabulation"],"data":{"confrab_factor":42},"app":["MyApp"],"msg":"Confrabulating widgets, with extra namespace and context","pid":"10456","loc":{"loc_col":11,"loc_pkg":"main","loc_mod":"Helpers.Logging","loc_fn":"Helpers\\Logging.hs","loc_ln":53},"host":"myhost.example.com","sev":"Debug","thread":"ThreadId 139"}
162146-- > {"at":"2018-10-02T21:50:30.4523848Z","env":"production","ns":["MyApp"],"data":{},"app":["MyApp"],"msg":"Namespace and context are back to normal","pid":"10456","loc":{"loc_col":9,"loc_pkg":"main","loc_mod":"Helpers.Logging","loc_fn":"Helpers\\Logging.hs","loc_ln":55},"host":"myhost.example.com","sev":"Info","thread":"ThreadId 139"}
163147jsonFormat :: LogItem a => ItemFormatter a
164−jsonFormat withColor verb i = textBuilderToBS $
165− appendNL $
148+jsonFormat withColor verb i =
149+ fromText $
166150 colorBySeverity withColor (_itemSeverity i) $
167− encodeToTextBuilder $ itemJson verb i
151+ toStrict $ decodeUtf8 $ encode $ itemJson verb i
168152
169153-- | Color a text message based on `Severity`. `ErrorS` and more severe errors
170154-- are colored red, `WarningS` is colored yellow, and all other messages are
171155-- rendered in the default color.
172−colorBySeverity :: Bool -> Severity -> TL.Builder -> TL.Builder
156+colorBySeverity :: Bool -> Severity -> Text -> Text
173157colorBySeverity withColor severity msg = case severity of
174158 EmergencyS -> red msg
175159 AlertS -> red msg