HORIZON HASKELLDocslts/ghc-9.10.xc74966e2026-09-27Search names, modules, packages, or :: a typeCtrl K

GHC 9.10.3 · lts/ghc-9.10.x · c74966e · 2026-09-27

Modulekatip-0.8.8.0Haskell2010

Katip

Includes all of the APIs youll need to use Katip. Be sure to check out the included examples directory for an example of usage.

Here's a basic example:


{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
import Control.Exception
import Katip

main :: IO ()
main = do
  handleScribe <- mkHandleScribe ColorIfTerminal stdout (permitItem InfoS) V2
  let makeLogEnv = registerScribe "stdout" handleScribe defaultScribeSettings =<< initLogEnv "MyApp" "production"
  -- closeScribes will stop accepting new logs, flush existing ones and clean up resources
  bracket makeLogEnv closeScribes $ \le -> do
    let initialContext = () -- this context will be attached to every log in your app and merged w/ subsequent contexts
    let initialNamespace = "main"
    runKatipContextT le initialContext initialNamespace $ do
      $(logTM) InfoS "Hello Katip"
      -- This adds a namespace to the current namespace and merges a piece of contextual data into your context
      katipAddNamespace "additional_namespace" $ katipAddContext (sl "some_context" True) $ do
        $(logTM) WarningS "Now we're getting fancy"
      katipNoLogging $ do
        $(logTM) DebugS "You will never see this!"

And here is the output:

[2021-06-14 20:24:24][MyApp.main][Info][yourhostname][PID 14420][ThreadId 27][main:Main app/Main.hs:26:9] Hello Katip
[2021-06-14 20:24:24][MyApp.main.additional_namespace][Warning][yourhostname][PID 14420][ThreadId 27][some_context:True][main:Main app/Main.hs:29:11] Now we're getting fancy

Another common case that you have some sort of App monad that's based on ReaderT with some Config state. This is a perfect place to insert read-only katip state:


import Katip as K

data Config = Config {
  logNamespace :: K.Namespace
, logContext :: K.LogContexts
, logEnv :: K.LogEnv
-- whatever other read-only config you need
}

newtype App m a = App {
  unApp :: ReaderT Config m a
} deriving (Functor, Applicative, Monad, MonadIO, MonadReader Config) -- these are necessary


-- These instances get even easier with lenses!
instance (MonadIO m) => K.Katip (App m) where
  getLogEnv = asks logEnv
  -- with lens:
  -- getLogEnv = view logEnv
  localLogEnv f (App m) = App (local (\s -> s { logEnv = f (logEnv s)}) m)
  -- with lens:
  -- localLogEnv f (App m) = App (local (over logEnv f) m)


instance (MonadIO m) => K.KatipContext (App m) where
  getKatipContext = asks logContext
  -- with lens:
  -- getKatipContext = view logContext
  localKatipContext f (App m) = App (local (\s -> s { logContext = f (logContext s)}) m)
  -- with lens:
  -- localKatipContext f (App m) = App (local (over logContext f) m)
  getKatipNamespace = asks logNamespace
  -- with lens:
  -- getKatipNamespace = view logNamespace
  localKatipNamespace f (App m) = App (local (\s -> s { logNamespace = f (logNamespace s)}) m)
  -- with lens:
  -- localKatipNamespace f (App m) = App (local (over logNamespace f) m)

To get up and running, the workflow is generally:

  • Set up a LogEnv using initLogEnv.

  • Add Scribes using registerScribe.

  • Either use KatipT or KatipContextT for a pre-built transformer stack or add Katip and KatipContext instances to your own transformer stack. If you do the latter, you may want to look in the examples dir for some tips on composing contexts and namespaces.

  • Define some structured log data throughout your application and implement ToObject and LogItem for them.

  • Begin logging with logT, logTM, etc.

  • Define your own Scribe if you need to output to some as-yet unsupported format or service. If you think it would be useful to others, consider releasing your own package.

  • 19 types
  • 4 classes
  • 60 values
  • Packagekatip-0.8.8.0
  • Exports83
  • LanguageHaskell2010
  • LicenceBSD-3-Clause
  • SourceKatip.hs

Framework Types

19 declarations
newtypenewtype Namespace
#

Represents a heirarchy of namespaces going from general to specific. For instance: ["processname", "subsystem"]. Note that single-segment namespaces can be created using IsString/OverloadedStrings, so "foo" will result in Namespace ["foo"].

Constructors

Instances12Eq, Ord, Read, Show, IsString, Generic, …
newtypenewtype Environment
#

Application environment, like prod, devel, testing.

Instances9Eq, Ord, Read, Show, IsString, Generic, …
datadata Severity
#

Constructors

Instances11Bounded, Enum, Eq, Ord, Read, Show, …
datadata Verbosity
#

Verbosity controls the amount of information (columns) a Scribe emits during logging.

The convention is: - V0 implies no additional payload information is included in message. - V3 implies the maximum amount of payload information. - Anything in between is left to the discretion of the developer.

Instances11Bounded, Enum, Eq, Ord, Read, Show, …
classclass ToObject a where
#

Katip requires JSON objects to be logged as context. This typeclass provides a default instance which uses ToJSON and produces an empty object if toJSON results in any type other than object. If you have a type you want to log that produces an Array or Number for example, you'll want to write an explicit instance here. You can trivially add a ToObject instance for something with a ToJSON instance like:

instance ToObject Foo

Methods

Instances4ToObject
classclass ToObject a => LogItem a where
#

Payload objects need instances of this class. LogItem makes it so that you can have very verbose items getting logged with lots of extra fields but under normal circumstances, if your scribe is configured for a lower verbosity level, it will only log a selection of those keys. Furthermore, each Scribe can be configured with a different Verbosity level. You could even use registerScribe, unregisterScribe, and clearScribes to at runtime swap out your existing scribes for more verbose debugging scribes if you wanted to.

When defining payloadKeys, don't redundantly declare the same keys for higher levels of verbosity. Each level of verbosity automatically and recursively contains all keys from the level before it.

Methods

Instances3LogItem
datadata Item a
#
Instances7Functor, Eq, Show, Generic, FromJSON, ToJSON, …
datadata Scribe
#

Constructors

  • Scribe
    • liPush :: forall a. LogItem a => Item a -> IO ()

      How do we write an item to the scribe's output?

    • scribeFinalizer :: IO ()

      Provide a blocking finalizer to call when your scribe is removed. All pending writes should be flushed synchronously. If this is not relevant to your scribe, return () is fine.

    • scribePermitItem :: PermitFunc

      Provide a filtering function to allow the item to be logged, or not. It can check Severity or some string in item's body. The initial value of this is usually created from permitItem. Scribes and users can customize this by ANDing or ORing onto the default with permitAND or permitOR

Instances2Semigroup, Monoid
  • Semigroup ScribeDefined in katip-0.8.8.0 · Katip.Core

    Combine two scribes. Publishes to the left scribe if the left would permit the item and to the right scribe if the right would permit the item. Finalizers are called in sequence from left to right.

  • Monoid ScribeDefined in katip-0.8.8.0 · Katip.Core
datadata LogEnv
#

Constructors

newtypenewtype SimpleLogPayload
#
Instances5Semigroup, Monoid, ToJSON, LogItem, ToObject

lens-compatible Lenses

A Built-in Monad For Simple Logging

2 declarations
newtypenewtype KatipT (m :: Type -> Type) a
#

A concrete monad you can use to run logging actions. Use this if you prefer an explicit monad transformer stack and adding layers as opposed to implementing Katip for your monad.

Constructors

Instances18MonadTrans, MonadTransControl, MonadBase, MonadBaseControl, Monad, Functor, …

Initializing Loggers

2 declarations
valueinitLogEnv
  1. :: Namespace

    A base namespace for this application

  2. -> Environment

    Current run environment (e.g. prod vs. devel)

  3. -> IO LogEnv
#

Create a reasonable default InitLogEnv. Uses an AutoUpdate which updates the timer every 1ms. If you need even more timestamp precision at the cost of performance, consider setting _logEnvTimer with getCurrentTime.

valueregisterScribe
  1. :: Text

    Name the scribe

  2. -> Scribe
  3. -> ScribeSettings
  4. -> LogEnv
  5. -> IO LogEnv
#

Add a scribe to the list. All future log calls will go to this scribe in addition to the others. Writes will be buffered per the ScribeSettings to prevent slow scribes from slowing down logging. Writes will be dropped if the buffer fills.

Dropping scribes temporarily

2 declarations
valueunregisterScribe
  1. :: Text

    Name of the scribe

  2. -> LogEnv
  3. -> LogEnv
#

Remove a scribe from the environment. This does not finalize the scribe. This mainly only makes sense to use with something like MonadReader's local function to temporarily disavow a single logger for a block of code.

valueclearScribes :: LogEnv -> LogEnv
#

Unregister all scribes. Note that this is not for closing or finalizing scribes, use closeScribes for that. This mainly only makes sense to use with something like MonadReader's local function to temporarily disavow any loggers for a block of code.

Finalizing scribes at shutdown

2 declarations
valuecloseScribes :: LogEnv -> IO LogEnv
#

Call this at the end of your program. This is a blocking call that stop writing to a scribe's queue, waits for the queue to empty, finalizes each scribe in the log environment and then removes it. Finalizers are all run even if one of them throws, but the exception will be re-thrown at the end.

valuecloseScribe
  1. :: Text

    Name of the scribe

  2. -> LogEnv
  3. -> IO LogEnv
#

Finalize a scribe. The scribe is removed from the environment, its finalizer is called so that it can never be written to again and all pending writes are flushed. Note that this will throw any exceptions yoru finalizer will throw, and that LogEnv is immutable, so it will not be removed in that case.

Logging Functions

4 declarations
newtypenewtype LogStr
#

Log message with Builder underneath; use <> to concat in O(1).

Constructors

Instances8Eq, Show, IsString, Generic, Semigroup, Monoid, …

Katip Logging Functions

These logging functions use the basic Katip constraint and thus will require varying degrees of explicit detail such as Namespace and individual log items to be passed in. These can be described as the primitives of Katip logging. If you find yourself making multiple log statements within a logical logging context for your app, you may want to look into the KatipContext family of logging functions like logFM and logTM. KatipContext in most applications should be considered the default. Here's an example of the pain point:

doDatabaseThings = do
 connId <- getConnectionId
 logF (ConnectionIDContext connId) "database" InfoS "Doing database stuff"
 -- ...
 logF (ConnectionIDContext connId) "database" InfoS "Wow, passing in the same context is getting tedious"

Another pain point to look out for is nesting actions that log in each other. Let's say you were writing a web app. You want to capture some detail such as the user's ID in the logs, but you also want that info to show up in doDatabaseThings' logs so you can associate those two pieces of information:

webRequestHandler = do
 uid <- getUserId
 logF (UserIDContext uid) "web" InfoS "Starting web request"
 doDatabaseThings

In the above example, doDatabaseThings would overwrite that UserIDContext with its own context and namespace. Sometimes this is what you want and that's why logF and other functions which only require Katip exist. If you are interested in combining log contexts and namespaces, see KatipContext.

classclass MonadIO m => Katip (m :: Type -> Type) where
#

Monads where katip logging actions can be performed. Katip is the most basic logging monad. You will typically use this directly if you either don't want to use namespaces/contexts heavily or if you want to pass in specific contexts and/or namespaces at each log site.

For something more powerful, look at the docs for KatipContext, which keeps a namespace and merged context. You can write simple functions that add additional namespacing and merges additional context on the fly.

localLogEnv was added to allow for lexically-scoped modifications of the log env that are reverted when the supplied monad completes. katipNoLogging, for example, uses this to temporarily pause log outputs.

Methods

Instances13Katip, …
valuelogT :: ExpQ
#

Loc-tagged logging when using template-haskell.

$(logT) obj mempty InfoS "Hello world"
valuelogLoc
  1. :: (Applicative m, LogItem a, Katip m, HasCallStack)
  2. => a
  3. -> Namespace
  4. -> Severity
  5. -> LogStr
  6. -> m ()
#

Loc-tagged logging using GHC.Stack when available.

This function does not require template-haskell as it automatically uses implicit-callstacks when the code is compiled using GHC > 7.8. Using an older version of the compiler will result in the emission of a log line without any location information, so be aware of it. Users using GHC <= 7.8 may want to use the template-haskell function logT for maximum compatibility.

logLoc obj mempty InfoS "Hello world"
valuelogKatipItem :: (Applicative m, LogItem a, Katip m) => Item a -> m ()
#

Log already constructed Item. This is the lowest level function that other log* functions use. It can be useful when implementing centralised logging services.

valuelogException
  1. :: (Katip m, LogItem a, MonadCatch m, Applicative m)
  2. => a

    Log context

  3. -> Namespace

    Namespace

  4. -> Severity

    Severity

  5. -> m b

    Main action being run

  6. -> m b
#

Perform an action while logging any exceptions that may occur. Inspired by onException.

Example1 expression
> logException () mempty ErrorS (error "foo")

KatipContext: Logging With Context

These logging functions use the KatipContext constraint which is a superclass of Katip that also has a mechanism for keeping track of the current context and namespace. This means a few things:

  1. Functions that use KatipContext like logFM and logTM do not require you to pass in LogItems or Namespaces, they pull them from the monadic environment.

  2. It becomes easy to add functions which add namespaces and/or contexts to the current stack of them. You can (and should) make that action scoped to a monadic action so that when it finishes, the previous context and namespace will be automatically restored.

KatipContextT provides a simple, ReaderT-based implementation of the KatipContext typeclass, and provides katipAddContext and katipAddNamespace functions to append to the context for the duration of a block:

main = do
 le <- initLogEnv MyApp "production"
 -- set up scribes here
 runKatipContext le () "main" $ do
   katipAddNamespace "nextlevel" $ do
     $(logTM) InfoS "Logs here will have namespace MyApp.main.nextlevel"

   katipAddContext TrivialContext $ do
     $(logTM) InfoS "Logs here will have context from TrivialContext"

     katipAddContext AnotherContext $ do
       $(logTM) InfoS "Logs here will have context from TrivialContext *merged with* context from AnotherContext!"

   $(logTM) InfoS "Log context restored to () and namespace to MyApp.main"

katipAddNamespace and katipAddContext are one-liners, implemented in terms of local from MonadReader. If you have a custom monad transformer stack and want to add your own version of these, check out <https://github.com/Soostone/katip/tree/master/katip/examples these examples>.

classclass Katip m => KatipContext (m :: Type -> Type) where
#

A monadic context that has an inherant way to get logging context and namespace. Examples include a web application monad or database monad. The local variants are just like local from Reader and indeed you can easily implement them with local if you happen to be using a Reader in your monad. These give us katipAddNamespace and katipAddContext that works with *any* KatipContext, as opposed to making users have to implement these functions on their own in each app.

Methods

Instances14KatipContext, …
valuelogFM
  1. :: (Applicative m, KatipContext m)
  2. => Severity

    Severity of the message

  3. -> LogStr

    The log message

  4. -> m ()
#

Log with full context, but without any code location. Automatically supplies payload and namespace.

valuelogTM :: ExpQ
#

Loc-tagged logging when using template-haskell. Automatically supplies payload and namespace.

$(logTM) InfoS "Hello world"

Loc-tagged logging when using getCallStack implicit-callstacks>. Automatically supplies payload and namespace.

Same consideration as logLoc applies.

By default, location will be logged from the module that invokes logLocM. If you want to use logLocM in a helper, wrap the entire helper in withFrozenCallStack to retain the callsite of the helper in the logs.

This function does not require template-haskell. Using GHC <= 7.8 will result in the emission of a log line without any location information. Users using GHC <= 7.8 may want to use the template-haskell function logTM for maximum compatibility.

logLocM InfoS "Hello world"
datadata AnyLogContext where
#

A wrapper around a log context that erases type information so that contexts from multiple layers can be combined intelligently.

newtypenewtype LogContexts
#

Heterogeneous list of log contexts that provides a smart LogContext instance for combining multiple payload policies. This is critical for log contexts deep down in a stack to be able to inject their own context without worrying about other context that has already been set. Also note that contexts are treated as a sequence and <> will be appended to the right hand side of the sequence. If there are conflicting keys in the contexts, the /right side will take precedence/, which is counter to how monoid works for Map and HashMap, so bear that in mind. The reasoning is that if the user is sequentially adding contexts to the right side of the sequence, on conflict the intent is to overwrite with the newer value (i.e. the rightmost value).

Additional note: you should not mappend LogContexts in any sort of infinite loop, as it retains all data, so that would be a memory leak.

Instances5Semigroup, Monoid, ToJSON, LogItem, ToObject
valueliftPayload :: LogItem a => a -> LogContexts
#

Lift a log context into the generic wrapper so that it can combine with the existing log context.

Temporarily Changing Logging Behavior

valuekatipAddNamespace :: KatipContext m => Namespace -> m a -> m a
#

Append a namespace segment to the current namespace for the given monadic action, then restore the previous state afterwards. Works with anything implementing KatipContext.

valuekatipAddContext :: (LogItem i, KatipContext m) => i -> m a -> m a
#

Append some context to the current context for the given monadic action, then restore the previous state afterwards. Important note: be careful using this in a loop. If you're using something like forever or replicateM_ that does explicit sharing to avoid a memory leak, youll be fine as it will *sequence* calls to katipAddNamespace, so each loop will get the same context added. If you instead roll your own recursion and you're recursing in the action you provide, you'll instead accumulate tons of redundant contexts and even if they all merge on log, they are stored in a sequence and will leak memory. Works with anything implementing KatipContext.

valuekatipNoLogging :: Katip m => m a -> m a
#

Disable all scribes for the given monadic action, then restore them afterwards. Works in any Katip monad.

Included Scribes

7 declarations

Logs to a file handle such as stdout, stderr, or a file. Contexts and other information will be flattened out into bracketed fields. For example:

[2016-05-11 21:01:15][MyApp][Info][myhost.example.com][PID 1724][ThreadId 1154][main:Helpers.Logging Helpers/Logging.hs:32:7] Started
[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
[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

Returns the newly-created Scribe. The finalizer flushes the handle. Handle mode is set to LineBuffering automatically.

A traditional bracketed log format. Contexts and other information will be flattened out into bracketed fields. For example:

[2016-05-11 21:01:15][MyApp][Info][myhost.example.com][PID 1724][ThreadId 1154][main:Helpers.Logging Helpers/Logging.hs:32:7] Started
[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
[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
valuejsonFormat :: LogItem a => ItemFormatter a
#

Logs items as JSON. This can be useful in circumstances where you already have infrastructure that is expecting JSON to be logged to a standard stream or file. For example:

{"at":"2018-10-02T21:50:30.4523848Z","env":"production","ns":["MyApp"],"data":{},"app":["MyApp"],"msg":"Started","pid":"10456","loc":{"loc_col":9,"loc_pkg":"main","loc_mod":"Helpers.Logging","loc_fn":"Helpers\\Logging.hs","loc_ln":44},"host":"myhost.example.com","sev":"Info","thread":"ThreadId 139"}
{"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"}
{"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"}

Tools for implementing Scribes

6 declarations
typetype PermitFunc = forall a. Item a -> IO Bool
#

Scribes are handlers of incoming items. Each registered scribe knows how to push a log item somewhere.

Guidelines for writing your own Scribe

Scribes should always take a Severity and Verbosity.

Severity is used to exclude log messages that are lower than the provided Severity. For instance, if the user passes InfoS, DebugS items should be ignored. Katip provides the permitItem utility for this. The user or the scribe may use permitAND and permitOR to further customize this filtering, even dynamically if they wish to.

Verbosity is used to select keys from the log item's payload. Each LogItem instance describes what keys should be retained for each Verbosity level. Use the payloadObject utility for extracting the keys that should be written.

Scribes provide a finalizer IO action (scribeFinalizer) that is meant to synchronously flush any remaining writes and clean up any resources acquired when the scribe was created. Internally, katip keeps a buffer for each scribe's writes. When closeScribe or closeScribes is called, that buffer stops accepting new log messages and after the last item in its buffer is sent to liPush, calls the finalizer. Thus, when the finalizer returns, katip can assume that all resources are cleaned up and all log messages are durably written.

While katip internally buffers messages per ScribeSettings, it sends them one at a time to the scribe. Depending on the scribe itself, it may make sense for that scribe to keep its own internal buffer to batch-send logs if writing items one at a time is not efficient. The scribe implementer must be sure that on finalization, all writes are committed synchronously.

Signature of a function passed to Scribe constructor and mkScribe* functions that decides which messages to be logged. Typically filters based on Severity, but can be combined with other, custom logic with permitAND and permitOR

valuepayloadObject :: LogItem a => Verbosity -> a -> Object
#

Constrain payload based on verbosity. Backends should use this to automatically bubble higher verbosity levels to lower ones.

valueitemJson :: LogItem a => Verbosity -> Item a -> Value
#

Convert log item to its JSON representation while trimming its payload based on the desired verbosity. Backends that push JSON messages should use this to obtain their payload.

KatipContextT - Utility transformer that provides Katip and KatipContext instances

2 declarations
newtypenewtype KatipContextT (m :: Type -> Type) a
#

Provides a simple transformer that defines a KatipContext instance for a fixed namespace and context. Just like KatipT, you should use this if you prefer an explicit transformer stack and don't want to (or cannot) define KatipContext for your monad . This is the slightly more powerful version of KatipT in that it provides KatipContext instead of just Katip. For instance:

  threadWithLogging = do
    le <- getLogEnv
    ctx <- getKatipContext
    ns <- getKatipNamespace
    forkIO $ runKatipContextT le ctx ns $ do
      $(logTM) InfoS "Look, I can log in IO and retain context!"
      doOtherStuff
Instances25MonadTrans, MonadTransControl, MonadError, MonadReader, MonadState, MonadWriter, …