diff --git a/CHANGELOG.md b/CHANGELOG.md
new file mode 100644
--- /dev/null
+++ b/CHANGELOG.md
@@ -0,0 +1,5 @@
+# Revision history for co-log-json
+
+## 0.0.1.0 -- 2020-11-11
+
+* First version.
diff --git a/LICENSE b/LICENSE
new file mode 100644
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,373 @@
+Mozilla Public License Version 2.0
+==================================
+
+1. Definitions
+--------------
+
+1.1. "Contributor"
+    means each individual or legal entity that creates, contributes to
+    the creation of, or owns Covered Software.
+
+1.2. "Contributor Version"
+    means the combination of the Contributions of others (if any) used
+    by a Contributor and that particular Contributor's Contribution.
+
+1.3. "Contribution"
+    means Covered Software of a particular Contributor.
+
+1.4. "Covered Software"
+    means Source Code Form to which the initial Contributor has attached
+    the notice in Exhibit A, the Executable Form of such Source Code
+    Form, and Modifications of such Source Code Form, in each case
+    including portions thereof.
+
+1.5. "Incompatible With Secondary Licenses"
+    means
+
+    (a) that the initial Contributor has attached the notice described
+        in Exhibit B to the Covered Software; or
+
+    (b) that the Covered Software was made available under the terms of
+        version 1.1 or earlier of the License, but not also under the
+        terms of a Secondary License.
+
+1.6. "Executable Form"
+    means any form of the work other than Source Code Form.
+
+1.7. "Larger Work"
+    means a work that combines Covered Software with other material, in
+    a separate file or files, that is not Covered Software.
+
+1.8. "License"
+    means this document.
+
+1.9. "Licensable"
+    means having the right to grant, to the maximum extent possible,
+    whether at the time of the initial grant or subsequently, any and
+    all of the rights conveyed by this License.
+
+1.10. "Modifications"
+    means any of the following:
+
+    (a) any file in Source Code Form that results from an addition to,
+        deletion from, or modification of the contents of Covered
+        Software; or
+
+    (b) any new file in Source Code Form that contains any Covered
+        Software.
+
+1.11. "Patent Claims" of a Contributor
+    means any patent claim(s), including without limitation, method,
+    process, and apparatus claims, in any patent Licensable by such
+    Contributor that would be infringed, but for the grant of the
+    License, by the making, using, selling, offering for sale, having
+    made, import, or transfer of either its Contributions or its
+    Contributor Version.
+
+1.12. "Secondary License"
+    means either the GNU General Public License, Version 2.0, the GNU
+    Lesser General Public License, Version 2.1, the GNU Affero General
+    Public License, Version 3.0, or any later versions of those
+    licenses.
+
+1.13. "Source Code Form"
+    means the form of the work preferred for making modifications.
+
+1.14. "You" (or "Your")
+    means an individual or a legal entity exercising rights under this
+    License. For legal entities, "You" includes any entity that
+    controls, is controlled by, or is under common control with You. For
+    purposes of this definition, "control" means (a) the power, direct
+    or indirect, to cause the direction or management of such entity,
+    whether by contract or otherwise, or (b) ownership of more than
+    fifty percent (50%) of the outstanding shares or beneficial
+    ownership of such entity.
+
+2. License Grants and Conditions
+--------------------------------
+
+2.1. Grants
+
+Each Contributor hereby grants You a world-wide, royalty-free,
+non-exclusive license:
+
+(a) under intellectual property rights (other than patent or trademark)
+    Licensable by such Contributor to use, reproduce, make available,
+    modify, display, perform, distribute, and otherwise exploit its
+    Contributions, either on an unmodified basis, with Modifications, or
+    as part of a Larger Work; and
+
+(b) under Patent Claims of such Contributor to make, use, sell, offer
+    for sale, have made, import, and otherwise transfer either its
+    Contributions or its Contributor Version.
+
+2.2. Effective Date
+
+The licenses granted in Section 2.1 with respect to any Contribution
+become effective for each Contribution on the date the Contributor first
+distributes such Contribution.
+
+2.3. Limitations on Grant Scope
+
+The licenses granted in this Section 2 are the only rights granted under
+this License. No additional rights or licenses will be implied from the
+distribution or licensing of Covered Software under this License.
+Notwithstanding Section 2.1(b) above, no patent license is granted by a
+Contributor:
+
+(a) for any code that a Contributor has removed from Covered Software;
+    or
+
+(b) for infringements caused by: (i) Your and any other third party's
+    modifications of Covered Software, or (ii) the combination of its
+    Contributions with other software (except as part of its Contributor
+    Version); or
+
+(c) under Patent Claims infringed by Covered Software in the absence of
+    its Contributions.
+
+This License does not grant any rights in the trademarks, service marks,
+or logos of any Contributor (except as may be necessary to comply with
+the notice requirements in Section 3.4).
+
+2.4. Subsequent Licenses
+
+No Contributor makes additional grants as a result of Your choice to
+distribute the Covered Software under a subsequent version of this
+License (see Section 10.2) or under the terms of a Secondary License (if
+permitted under the terms of Section 3.3).
+
+2.5. Representation
+
+Each Contributor represents that the Contributor believes its
+Contributions are its original creation(s) or it has sufficient rights
+to grant the rights to its Contributions conveyed by this License.
+
+2.6. Fair Use
+
+This License is not intended to limit any rights You have under
+applicable copyright doctrines of fair use, fair dealing, or other
+equivalents.
+
+2.7. Conditions
+
+Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
+in Section 2.1.
+
+3. Responsibilities
+-------------------
+
+3.1. Distribution of Source Form
+
+All distribution of Covered Software in Source Code Form, including any
+Modifications that You create or to which You contribute, must be under
+the terms of this License. You must inform recipients that the Source
+Code Form of the Covered Software is governed by the terms of this
+License, and how they can obtain a copy of this License. You may not
+attempt to alter or restrict the recipients' rights in the Source Code
+Form.
+
+3.2. Distribution of Executable Form
+
+If You distribute Covered Software in Executable Form then:
+
+(a) such Covered Software must also be made available in Source Code
+    Form, as described in Section 3.1, and You must inform recipients of
+    the Executable Form how they can obtain a copy of such Source Code
+    Form by reasonable means in a timely manner, at a charge no more
+    than the cost of distribution to the recipient; and
+
+(b) You may distribute such Executable Form under the terms of this
+    License, or sublicense it under different terms, provided that the
+    license for the Executable Form does not attempt to limit or alter
+    the recipients' rights in the Source Code Form under this License.
+
+3.3. Distribution of a Larger Work
+
+You may create and distribute a Larger Work under terms of Your choice,
+provided that You also comply with the requirements of this License for
+the Covered Software. If the Larger Work is a combination of Covered
+Software with a work governed by one or more Secondary Licenses, and the
+Covered Software is not Incompatible With Secondary Licenses, this
+License permits You to additionally distribute such Covered Software
+under the terms of such Secondary License(s), so that the recipient of
+the Larger Work may, at their option, further distribute the Covered
+Software under the terms of either this License or such Secondary
+License(s).
+
+3.4. Notices
+
+You may not remove or alter the substance of any license notices
+(including copyright notices, patent notices, disclaimers of warranty,
+or limitations of liability) contained within the Source Code Form of
+the Covered Software, except that You may alter any license notices to
+the extent required to remedy known factual inaccuracies.
+
+3.5. Application of Additional Terms
+
+You may choose to offer, and to charge a fee for, warranty, support,
+indemnity or liability obligations to one or more recipients of Covered
+Software. However, You may do so only on Your own behalf, and not on
+behalf of any Contributor. You must make it absolutely clear that any
+such warranty, support, indemnity, or liability obligation is offered by
+You alone, and You hereby agree to indemnify every Contributor for any
+liability incurred by such Contributor as a result of warranty, support,
+indemnity or liability terms You offer. You may include additional
+disclaimers of warranty and limitations of liability specific to any
+jurisdiction.
+
+4. Inability to Comply Due to Statute or Regulation
+---------------------------------------------------
+
+If it is impossible for You to comply with any of the terms of this
+License with respect to some or all of the Covered Software due to
+statute, judicial order, or regulation then You must: (a) comply with
+the terms of this License to the maximum extent possible; and (b)
+describe the limitations and the code they affect. Such description must
+be placed in a text file included with all distributions of the Covered
+Software under this License. Except to the extent prohibited by statute
+or regulation, such description must be sufficiently detailed for a
+recipient of ordinary skill to be able to understand it.
+
+5. Termination
+--------------
+
+5.1. The rights granted under this License will terminate automatically
+if You fail to comply with any of its terms. However, if You become
+compliant, then the rights granted under this License from a particular
+Contributor are reinstated (a) provisionally, unless and until such
+Contributor explicitly and finally terminates Your grants, and (b) on an
+ongoing basis, if such Contributor fails to notify You of the
+non-compliance by some reasonable means prior to 60 days after You have
+come back into compliance. Moreover, Your grants from a particular
+Contributor are reinstated on an ongoing basis if such Contributor
+notifies You of the non-compliance by some reasonable means, this is the
+first time You have received notice of non-compliance with this License
+from such Contributor, and You become compliant prior to 30 days after
+Your receipt of the notice.
+
+5.2. If You initiate litigation against any entity by asserting a patent
+infringement claim (excluding declaratory judgment actions,
+counter-claims, and cross-claims) alleging that a Contributor Version
+directly or indirectly infringes any patent, then the rights granted to
+You by any and all Contributors for the Covered Software under Section
+2.1 of this License shall terminate.
+
+5.3. In the event of termination under Sections 5.1 or 5.2 above, all
+end user license agreements (excluding distributors and resellers) which
+have been validly granted by You or Your distributors under this License
+prior to termination shall survive termination.
+
+************************************************************************
+*                                                                      *
+*  6. Disclaimer of Warranty                                           *
+*  -------------------------                                           *
+*                                                                      *
+*  Covered Software is provided under this License on an "as is"       *
+*  basis, without warranty of any kind, either expressed, implied, or  *
+*  statutory, including, without limitation, warranties that the       *
+*  Covered Software is free of defects, merchantable, fit for a        *
+*  particular purpose or non-infringing. The entire risk as to the     *
+*  quality and performance of the Covered Software is with You.        *
+*  Should any Covered Software prove defective in any respect, You     *
+*  (not any Contributor) assume the cost of any necessary servicing,   *
+*  repair, or correction. This disclaimer of warranty constitutes an   *
+*  essential part of this License. No use of any Covered Software is   *
+*  authorized under this License except under this disclaimer.         *
+*                                                                      *
+************************************************************************
+
+************************************************************************
+*                                                                      *
+*  7. Limitation of Liability                                          *
+*  --------------------------                                          *
+*                                                                      *
+*  Under no circumstances and under no legal theory, whether tort      *
+*  (including negligence), contract, or otherwise, shall any           *
+*  Contributor, or anyone who distributes Covered Software as          *
+*  permitted above, be liable to You for any direct, indirect,         *
+*  special, incidental, or consequential damages of any character      *
+*  including, without limitation, damages for lost profits, loss of    *
+*  goodwill, work stoppage, computer failure or malfunction, or any    *
+*  and all other commercial damages or losses, even if such party      *
+*  shall have been informed of the possibility of such damages. This   *
+*  limitation of liability shall not apply to liability for death or   *
+*  personal injury resulting from such party's negligence to the       *
+*  extent applicable law prohibits such limitation. Some               *
+*  jurisdictions do not allow the exclusion or limitation of           *
+*  incidental or consequential damages, so this exclusion and          *
+*  limitation may not apply to You.                                    *
+*                                                                      *
+************************************************************************
+
+8. Litigation
+-------------
+
+Any litigation relating to this License may be brought only in the
+courts of a jurisdiction where the defendant maintains its principal
+place of business and such litigation shall be governed by laws of that
+jurisdiction, without reference to its conflict-of-law provisions.
+Nothing in this Section shall prevent a party's ability to bring
+cross-claims or counter-claims.
+
+9. Miscellaneous
+----------------
+
+This License represents the complete agreement concerning the subject
+matter hereof. If any provision of this License is held to be
+unenforceable, such provision shall be reformed only to the extent
+necessary to make it enforceable. Any law or regulation which provides
+that the language of a contract shall be construed against the drafter
+shall not be used to construe this License against a Contributor.
+
+10. Versions of the License
+---------------------------
+
+10.1. New Versions
+
+Mozilla Foundation is the license steward. Except as provided in Section
+10.3, no one other than the license steward has the right to modify or
+publish new versions of this License. Each version will be given a
+distinguishing version number.
+
+10.2. Effect of New Versions
+
+You may distribute the Covered Software under the terms of the version
+of the License under which You originally received the Covered Software,
+or under the terms of any subsequent version published by the license
+steward.
+
+10.3. Modified Versions
+
+If you create software not governed by this License, and you want to
+create a new license for such software, you may create and use a
+modified version of this License if you rename the license and remove
+any references to the name of the license steward (except to note that
+such modified license differs from this License).
+
+10.4. Distributing Source Code Form that is Incompatible With Secondary
+Licenses
+
+If You choose to distribute Source Code Form that is Incompatible With
+Secondary Licenses under the terms of this version of the License, the
+notice described in Exhibit B of this License must be attached.
+
+Exhibit A - Source Code Form License Notice
+-------------------------------------------
+
+  This Source Code Form is subject to the terms of the Mozilla Public
+  License, v. 2.0. If a copy of the MPL was not distributed with this
+  file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+If it is not possible or desirable to put the notice in a particular
+file, then You may include the notice in a location (such as a LICENSE
+file in a relevant directory) where a recipient would be likely to look
+for such a notice.
+
+You may add additional accurate notices of copyright ownership.
+
+Exhibit B - "Incompatible With Secondary Licenses" Notice
+---------------------------------------------------------
+
+  This Source Code Form is "Incompatible With Secondary Licenses", as
+  defined by the Mozilla Public License, v. 2.0.
diff --git a/Readme.md b/Readme.md
new file mode 100644
--- /dev/null
+++ b/Readme.md
@@ -0,0 +1,236 @@
+# co-log-json
+
+`co-log-json` allows writing structured logs in your application.
+
+The library allows adding additional machine-readable context to the log
+messages. I.e. each log message is a JSON object with a predefined structure
+where additional user context can be added. Such logs can be easily indexed
+by external logs systems such as [Graylog](https://www.graylog.org) or 
+[Elastic search](https://www.elastic.co). The message logging is done using
+a special context, that keeps the information about additional attributes.
+Such contexts form a nested scope, and all messages in the score inherit provided
+context:
+
+```
+   scope [ user = "Joe"] 
+     |
+     | ==>  {"message":"user arrived", "data": { "user": "Joe"}
+     |
+     +------ scope [ tag = "human" ]
+              |
+              | ==> {"message": "user entered the door", "data": { "user": "Joe", "tag": "human"}
+```
+
+
+In other words, this library takes two choices:
+
+  1. We write full context with each message.
+  This approach allows using external tools (like elastic-search) that can index message
+  without any additional work and information.
+  Any message can be lost without affecting the ability to decode other messages. An alternative
+  approach could be emitting a list of events (possibly as a bytecode), such an approach
+  is taken by the tracing libraries. It requires more works during reading and indexing
+  logs, and in the case in some logs are logs may render later ones unusable or lose some info.
+
+  2. We keep a state context so we don't need to attach context messages to each one.
+  An alternative approach is the extraction of the structure information from the message itself.
+  This approach is taken in some structured logging libraries, it can provide better error
+  messages. However, it requires to think about the message context all the time (and developer 
+  user may not even know all interesting context where the message will be used).
+
+
+# Using a library
+
+To to use a library you'll need to add `co-log-json` to the dependency list.
+
+```
+library.cabal
+
+library
+  build-depends:
+    base,
+    co-log-json ^>= 0.0
+```
+
+
+## Setting the library
+
+
+```haskell
+import Colog.Json                       -- Core API for structured logging
+import Colog.Json.Action (logToHandle)  -- Actions to store the message
+import System.IO (stderr)
+
+main :: IO ()
+main = do
+  -- First, we need to set up log storing function:
+  --   To emit logs we need to create a context.
+  --    Context takes the action to store log and it's possible to
+  --    attach additional information to it.
+
+  let context = mkLogger (logToHandle stderr)
+  --                          ^
+  --                          |
+  --                          +------  `LogAction IO Message` 
+  --                                    (see discussion "Why IO below")
+  --
+  -- Once 'context' is created it can be passed to the other parts
+  -- of the code or used to emit logs.
+
+  logDebug context "Hi, there!"
+  --         ^         ^
+  --         |         |
+  --         |         +----- `LogStr` type - is an efficient text builder.
+  --         |                 
+  --         |
+  --         +-- log context
+
+  -- Will output:
+  --
+  -- ```
+  -- {"severity":"DEBUG", "thread": 1, "message": "Hi, there!"}
+  -- ```
+  --                ^               ^                ^
+  --                |               |                +------------ Message itself
+  --                |               +----------------------------- Id of the thread that emitted the message
+  --                +----------------- Severity level: Debug, Info, Notice, Error, Critical, Alert, Emergency
+  -- 
+  -- to the stderr.
+
+  -- There are other helper functions list `logInfo`, `logNotice`, etc.
+```
+
+Now let's discuss `LogStr` type. It exists to efficiently generate message without
+extra allocations that can be avoided. It's just a [Text.Builder](http://hackage.haskell.org/package/text-1.2.4.0/docs/Data-Text-Lazy-Builder.html) though internal
+representation may evolve in the future. `LogStr` allows message concatenation without allocating
+intermediate structures, so it allows efficient log building. For example line:
+
+```haskell
+  logDebug context $ "a" <> "b" <> "c"
+```
+
+will write all text string "a", "b", "c" directly to the buffer, and can do more optimizations.
+So it's quite safe to use the library even with a large number of logs.
+
+The 'LogStr' type implement [IsString](http://hackage.haskell.org/package/base-4.14.0.0/docs/Data-String.html#t:IsString) instance it means that you can just write string literals
+and they will be treated as 'LogStr'. To concatenate two 'LogStr' you can use [`<>`](https://hackage.haskell.org/package/base-4.14.0.0/docs/Data-Semigroup.html#t:Semigroup) operation.
+
+In addition you can convert any string lines that has [StringConv a T.Text](https://hackage.haskell.org/package/string-conv-0.1.2/docs/Data-String-Conv.html), i.e. can be converted
+to LogStr using `ls :: StringConv a T.Text => a -> LogStr`.
+Efficiency and safety of this conversion depends on the concrete instance implementation and is out
+of control of the package.
+
+```haskell
+   logDebug context $ "foo is " <> ls ("ы":: ByteString)
+```
+
+In case your data structure does not implement `StringConv a` it's possible to use not efficient but
+very general `showLS :: Show a => a -> LogStr` method that will work for any type that has Show instance.
+
+## Adding context.
+
+But just writing JSON messages is not very interesting, we want to control the context of the message.
+In order to add user data to the context we can use `addContext :: PushContext -> LoggerEnv -> LoggerEnv`
+method.
+
+```haskell
+
+   let context1 = addContext (sl "user_id" (1::Int)) context
+   --    ^                    ^     ^         ^        ^
+   --    |                    |     |         |        +--- old context
+   --    |                    |     |         +------------ user data 
+   --    |                    |     +---------------------- key for the user data
+   --    |                    +---------------------------- function that generates an entry
+   --    +------------------------------------------------- new context that has data attached
+
+   logDebug context1 "Hi again!"
+
+   -- Will emit to the stderr:
+   --
+   -- ```
+   -- {"severity":"DEBUG", "thread": 1, "message": "Hi, there!", "data": {"user_id":1}}
+   -- ```
+   --                                                              ^           ^    ^
+   --                                                              |           |    +-- value
+   --                                                              |           +------- key
+   --                                                              +--- all user data is kept under 'data' key
+```
+
+Sidenote: 'sl' function looks redundant, but it's needed in order to provide a future
+compatibility for a case when internal structure of user data is changing. Historically
+it came from [katip](https://hackage.haskell.org/package/katip) library, there are more functions that allows context creation but
+
+Function `sl :: ToJSON a => T.Text -> a -> PushContext` prepares update to the context. 
+It encodes user data to JSON. This is why we had to add type annotation to `1` otherwise GHC had
+no means to infer the type).
+
+It's important that the library does not perform any compaction of key-values, i.e.:
+
+```haskell
+   logDebug (addContext (sl "user_id" 2) context1) "Who am I?"
+   -- Will emit:
+   -- ```
+   -- {"severity":"DEBUG", "thread": 1, "message": "Hi, there!", "data": {"user_id":1, "user_id": 2}}
+   -- ```
+```
+
+This is done for purpose, but may be a subject to change in the future major versions.
+
+`addContext` is not the only function that allows to modify context, there is the other one
+`addNamespace :: Text -> LoggerEnv -> LoggerEnv`, this function adds an entry about the 
+current namespace. Namespace is a nested list of strings that tells the logical part of 
+the codebase the log belongs to. It's kept separate fom the data, and it's possible to
+use in library filtering (using  [cfilter](https://kowainik.github.io/posts/2018-09-25-co-log#cfilter)) or filtering in external system.
+
+
+The described functionality is enough to perform logging. However, it may worth discussing 
+interoperability with the rest of co-log ecosystem and ergonomics.
+
+## co-log interoperability
+
+The co-log ecosystem works with "LogAction m a" and in the package, we use "LogEnv" it means
+that we are losing most of the benefits of the library and can't use a lot of utility
+functions. To improve the situation it's possible to convert LogEnv into
+`LogAction m (Severity,LogStr)` using function `unLogger`. Then we will have log action
+that will emit a message with the current context, but the context will no longer be modifiable.
+
+# Ergonomics
+
+The package provides no ergonomic tools by default and it's important that `addContext` is a pure
+function. On the one han,d it introduces a log of boilerplate code but on the other.
+
+It allows to modify context even outside of the effectful computation for example with servant you may have:
+
+```haskell
+-- | Catalogue of items 
+data CatalogueApi route = CatalogueApi
+  { _the_catalogue :: route :- Capture "catalogue_id" CatalogueId :> ToServantAPI Bar
+  , ...
+  } 
+
+-- Item
+data ItemApi route = ItemApi
+  { _items :: route :- "items" :> Get '[JSON] (Vector Item)
+  , ...
+  }
+
+handleCatalogue :: LoggerEnv -> ToServant CatalogueApi AsServer
+handleCatalogue ctx' = CatalogueApi
+  { _the_catalogue = \catalogue_id ->
+     handleItem (addContext "catalogue_id" catalogue_id) ctx) catalogue_id
+  , ...
+  }
+  where 
+    ctx = addNamespace "catalogue" ctx'
+
+handleItem :: LoggerEnv -> CatalogueId -> ToServant ItemApi AsServer
+handleItem ctx' catalogue_id = ItemApi ...
+  where ctx = addNamespace "item" ctx'
+```
+
+So we can build computation that we will execute later while modifying the context.
+
+On the other hand, we can always wrap this pure function into an effect system 
+of choice be it either handle pattern or readert or MTL or effect system.
+This library does not target any particular solution and  want to introduce 
+neither additional dependencies nor additional restrictions on the user.
diff --git a/Setup.hs b/Setup.hs
new file mode 100644
--- /dev/null
+++ b/Setup.hs
@@ -0,0 +1,2 @@
+import Distribution.Simple
+main = defaultMain
diff --git a/co-log-json.cabal b/co-log-json.cabal
new file mode 100644
--- /dev/null
+++ b/co-log-json.cabal
@@ -0,0 +1,76 @@
+cabal-version:       3.0
+name:                co-log-json
+version:             0.0.1.0
+synopsis:            Structured messages support in co-log ecosystem.
+description:
+
+   The library implements of a very simple approach to structured logging, that
+   ca be used with the [co-log](https://hackage.haskell.org/package/co-log)
+   ecosystem or on it's own see [cheops-logger](https://github.com/cheopslab/cheops-logger).
+
+   It provides:
+
+     * "Colog.Json" — API for adding structured context to the log messages
+     * "Colog.Json.Action" — efficient function for dumping logs in the 
+       following format.
+
+   By default it emits logs in the following format (pretty-printed for convenience):
+
+   @
+   { "namespace":"server.package" -- namespace for the component
+   , "severity": \"DEBUG\"          -- severity level
+   , "thread":19                  -- id of the thread that emitted the message
+   , "message":"some long text "  -- textual message itself
+   , "data":                      -- user data
+      { "ip":"8.8.8.8"
+      , "http.request_id":"b362cd5db5c193c05312af4d3a399955"
+      , "http.method":\"DELETE\"
+      , "http.path":"\/url\/"
+      , "user_id":"123"
+      } 
+   }
+   @
+
+   The most interesting thing here is the field @data@ that can be used by the user
+   to add additional structured info to the message.
+
+bug-reports:         https://github.com/cheopslab/cheops-logger/issues/new?labels=co-log-json
+license:             MPL-2.0
+license-file:        LICENSE
+author:              Alexander Vershilov
+maintainer:          alexander.vershilov@sirius.online
+copyright:           (C) 2019-2020 Фонд Талант и Успех
+category:            System
+extra-source-files: 
+  CHANGELOG.md
+  Readme.md
+
+library
+  exposed-modules:
+    Colog.Json
+    Colog.Json.Action
+    Colog.Json.Message
+    Colog.Json.Internal.Structured
+  default-extensions:
+    BlockArguments
+    DerivingStrategies
+    FlexibleContexts
+    GeneralizedNewtypeDeriving
+    LambdaCase
+    OverloadedStrings
+    RecordWildCards
+  other-extensions:
+    UnliftedFFITypes
+    MagicHash
+    FlexibleContexts
+  build-depends:
+      base >=4.11 && <5
+    , aeson ^>= 1.5
+    , bytestring ^>=0.10
+    , text ^>=1.2
+    , containers ^>=0.6
+    , co-log-core ^>=0.2
+    , string-conv ^>=0.1
+  hs-source-dirs:      src
+  ghc-options:         -Wall
+  default-language:    Haskell2010
diff --git a/src/Colog/Json.hs b/src/Colog/Json.hs
new file mode 100644
--- /dev/null
+++ b/src/Colog/Json.hs
@@ -0,0 +1,205 @@
+-- |
+-- Top-level module for structured logging support.  Structured logging provides messages in
+-- a machine-readable format and passing an additional user data to the messages (context)
+-- to the log messages, and tooling that allows keep track of the current context and attach
+-- it to all the messages.
+--
+-- Short example:
+--
+-- @
+-- logic :: LoggerEnv -> Int -> IO ()
+-- logic ctx' entity_id = do                   -- (1)
+--    'logInfo' ctx "start processing entity"    -- (2)
+--    internal ctx entity_id                   -- (3)
+--    'logInfo' ctx "finish processing
+--   where
+--     ctx = 'addNamespace' "logic"              -- (4)
+--         . 'addContext' (sl "id" entity_id)    -- (5)
+--         $ ctx'
+-- @
+-- Here we:
+--
+--   * @(1)@ pass initial context (@ctx'@ :: 'LoggerEnv')
+--   * @(2)@ log message on 'InfoS' severtity level with new context attached
+--   * @(3)@ start internal fuction with new context
+--   * @(4)@ extend initial context with a new namespace
+--   * @(5)@ extend initial context with a new user data
+--
+-- __NOTE__ You may notice a bit of an extra boilerplate code here. It can be removed
+-- by using any effect handling approach, like ReaderT, MTL, various effects
+-- system or service pattern. However this library does not commit to any of
+-- those approaches and provides simple @IO@ interface, so there can be a light
+-- wrapper with the system of your choice. E.g. The library author prefer to use 
+-- @ImplicitParams@ extension, as you can see in cheops-logger package.
+--
+-- 
+module Colog.Json
+  ( -- $logger-env
+    LoggerEnv
+  , mkLogger
+  , emptyLogger
+  , unLogger
+    -- * Writing logs
+    -- $writing-logs
+  , ls
+  , showLS
+  , LogStr
+    -- $writing-helpers
+  , logDebug
+  , logNotice
+  , logInfo
+  , logErr
+  , logWarn
+  , logAlert
+  , logCrit
+  , logEmergency
+  , Severity(..)
+  
+    -- * Adding context
+    -- $adding-context
+  , addContext
+  , sl
+  , addNamespace
+  ) where
+
+import Colog.Core hiding (Severity)
+import Colog.Json.Internal.Structured
+import Control.Concurrent
+import Control.Monad.IO.Class
+import qualified Data.Sequence as Seq
+import qualified Data.Text as T
+
+-- $logger-env
+--
+-- For each message we attach additional information
+--
+--   * @thread id@ — it can be useful to group messages by the
+--     thread when debugging, especially in a case if a thread
+--     can be associated with the request processing.
+--
+--   * @namespace@ — '.' delimited text that describes the component
+--     that the log was emitted from. It allows simple logs
+--     filtering in an external system, or in the logger action.
+--
+--   * @severity@ — information how urgent the message is.
+--
+--   * @user_data@ - any user data in a key-value form, the key is a
+--       text value, and the value is a JSON-encoded value.
+--
+-- In order to keep track of that information we introduce 'LoggerEnv' handle.
+-- It can be used to emit messages with additional information,
+-- see writing logs section, and modify current context, see adding context section.
+
+-- | Logger environment is used to keep information about
+-- the current context and modify it. When any log message
+-- is emitted the current context is added to the message.
+data LoggerEnv = LoggerEnv
+  { action :: LogAction IO Message -- ^ Internal log action.
+  , context :: Seq.Seq Structured -- ^ Current context.
+  }
+
+-- | Logger that does nothing. Useful for the testing purpose.
+emptyLogger :: LoggerEnv
+emptyLogger = LoggerEnv (LogAction $ \_ -> pure ()) Seq.empty
+
+-- | Covert ordinary colog action into 'LoggerEnv' this way
+-- we can keep track of the current context and modify it.
+--
+-- @
+-- let ctx = 'mkLogger' ('Colog.Json.Action.logToHandle' 'System.IO.stderr')
+-- in 'logDebug' ctx "message"
+-- @
+-- 
+mkLogger :: LogAction IO Message -> LoggerEnv
+mkLogger action = LoggerEnv action Seq.empty
+
+-- | Covert 'LoggerEnv' back into colog 'LogAction', so we can
+-- combie it with the rest of the colog ecosystem.
+--
+-- @
+-- 'Colog.Core.Action.cfilter' (\\(sev, _) -> sev > 'Colog.Json.DebugS') 'unLogger' ctx
+-- @
+unLogger :: LoggerEnv -> LogAction IO (Severity, LogStr)
+unLogger (LoggerEnv action st) = LogAction $ \(lvl, msg) -> do
+  tid <- myThreadId
+  unLogAction action $ Message lvl (mkThreadId tid) st msg
+
+-- $adding-context
+--
+-- Messages in the library forms a stack, and you can attach 2 kinds of data to it:
+--
+--   1. @namespace@ - a list of locations, that allows to tell that the component
+--        is it.
+--   2. @context@ - context is a list of key-value pairs, where key is a text and
+--        a value is any JSON value.
+--
+-- When you attach that information to the 'LoggerContext' it will be added to
+-- each message that is written in that context. Allowing to analyze data in the
+-- external systems. User data is pushed as using 'PushContext' wrapper, that
+-- can be created using 'sl'.
+--
+
+-- | Helper to update context, by appending another item to the log.
+-- 
+-- @
+-- local ('addContext' ('sl' "key" "value")) $ do
+--   ...
+-- @
+addContext
+  :: PushContext -- ^ New data to store
+  -> LoggerEnv   -- ^ Old context.
+  -> LoggerEnv
+addContext (PushContext f) LoggerEnv{..} = LoggerEnv{context = f context, ..}
+
+-- | Helper to extend current namespace by appending sub-namespace.
+--
+-- @
+-- local ('addNamespace' "subcomponent") $ do
+--   ...
+-- @
+addNamespace :: T.Text -> LoggerEnv -> LoggerEnv
+addNamespace ns LoggerEnv{..} = LoggerEnv{context=context Seq.|> Segment ns, ..}
+
+-- $writing-logs
+-- Logs can we written using one of the following helpers. The general pattern is
+--
+-- @
+-- 'logDebug' logger "message"
+-- @
+--
+-- Messages has type 'LogStr'. This is an abstraction over a data-type for efficient
+-- log concatenation. Currently it uses 'Data.Text.Lazy.Builder' but it's an implementation
+-- detail and may change in the future.
+--
+-- 'LogStr' can be created is several ways:
+--
+--    * From the string literal using 'Data.String.IsString' interface
+--    * From the string like data that can be converted to text, using 'ls' function
+--    * From the type that has a 'Show' instance using 'showLS'
+--
+
+-- $writing-helpers
+-- Library provides helper for each 'Severity' level.
+
+logDebug, logNotice, logInfo, logWarn,
+  logErr, logAlert, logCrit, logEmergency
+  :: MonadIO m => LoggerEnv -> LogStr -> m ()
+logDebug  x = logSay x DebugS
+logNotice x = logSay x InfoS
+logInfo x = logSay x InfoS
+logWarn x = logSay x WarningS
+logErr x = logSay x ErrorS
+logCrit x = logSay x CriticalS
+logAlert x = logSay x AlertS
+logEmergency x = logSay x EmergencyS
+
+-- | Internal logger function.
+logSay :: MonadIO m
+       => LoggerEnv -- ^ Logger handle.
+       -> Severity -- ^ Message severity.
+       -> LogStr -- ^ Message itself.
+       -> m ()
+logSay (LoggerEnv action context) lvl msg = liftIO $ do
+  tid <- myThreadId
+  unLogAction action $ Message lvl (mkThreadId tid) context msg
+{-# SPECIALIZE logSay :: LoggerEnv -> Severity -> LogStr -> IO () #-}
diff --git a/src/Colog/Json/Action.hs b/src/Colog/Json/Action.hs
new file mode 100644
--- /dev/null
+++ b/src/Colog/Json/Action.hs
@@ -0,0 +1,109 @@
+-- |
+-- Action that allows to write structured log message.
+-- 
+module Colog.Json.Action
+  ( logToHandle
+  , encodeMessage
+  ) where
+
+import Colog.Core
+import Colog.Json.Internal.Structured
+import Control.Exception
+import Data.Aeson.Encoding as Aeson
+import qualified Data.ByteString.Builder as Builder
+import Data.Coerce
+import Data.Foldable
+import qualified Data.List.NonEmpty as NE
+import qualified Data.Text.Lazy as TL
+import qualified Data.Text.Lazy.Builder as TLB
+import System.IO
+
+-- | Dump logs to the output. On the contrary to the usual co-log functions this one
+-- embeds all the functionality inside. However all internals are exposed and in the
+-- case if you need any special functionality you can build your own function.
+--
+-- This function serializes a message to a temporary buffer and dumps buffer contents
+-- to the handle as soon as it's filled.  See 'encodeMessage' for encoding details.
+--
+-- Notes:
+--
+--   1. In case of exception this function tries to dump information about exception
+--      in the handle once. But if another exception arrives while storing info, 
+--      function rethorws the second exception.
+--
+--   2. During log dumping this function captures all exceptions (@SomeException@) including
+--      asynchronous ones. So it should be run under a mask.
+--
+--   3. Running a function under interruptible mask is safe as long no other thread 
+--      is using a @Handle@.
+--
+--   4. This function does not add timestamp to the message. This is done because
+--      we can always rely on external tools to add timestamp, whether it would be @ts@
+--      or @journald@ or docker-logger.
+--      However if timestamp from the program is strictly needed it's possible to add
+--      it to the user data.
+--
+--   5. If user data contains multiple values with the equal keys all the values will
+--      be stored. In case if it's unbearable you should remove duplicates when generating
+--      a @Message@
+--
+--   6. While dumping the message to the @Handle@ no lock is obtained, so the user
+--      is responsible for running this function in a race free context. It can be done
+--      either from a single thread, or using additional locking mechanisms.
+--
+--   8. This function relies on the line bufferring in order to dump logs promptly. It's
+--      up to the user to decide how to setup it but in case of block buffering during
+--      low activity logs may be delayed a lot.
+--
+logToHandle :: Handle -> LogAction IO Message
+logToHandle h = LogAction \m ->
+  let msg = encodeMessage m
+  in try (Builder.hPutBuilder h $ Aeson.fromEncoding msg <> Builder.char7 '\n') >>= \case
+       Left e -> do
+         Builder.hPutBuilder h $ Aeson.fromEncoding (Aeson.pairs
+            $ mconcat
+            [ Aeson.pair "namespace" (Aeson.text "logger")
+            , Aeson.pair "exception" (Aeson.string (show (e::SomeException)))
+            ])
+            <> Builder.char7 '\n'
+       Right _ -> pure ()
+
+
+-- | Efficiently convert a message into JSON encoding.
+--
+-- Message structure:
+-- 
+-- @
+-- { "namespace": "segment1.segment2"
+-- , "severity": "DEBUG"
+-- , "thread": 123121
+-- , "data":  { ... }
+-- , "message": "text message"
+-- }
+-- @
+-- 
+-- In case if there are no user attributes "data" key is omitted.
+encodeMessage :: Message -> Encoding
+{-# INLINE encodeMessage #-}
+encodeMessage Message{..} = Aeson.pairs $ mconcat fields where
+  fields =
+     [ case namespace of
+         Nothing -> mempty
+         Just xs -> Aeson.pair "namespace" $ Aeson.lazyText xs
+     , Aeson.pair "severity" $ encodeSeverity message_severity
+     , Aeson.pair "thread" $ Aeson.int thread_id
+     , case user_data of
+         Nothing -> mempty
+         Just xs -> Aeson.pair "data" $ Aeson.pairs xs
+     , Aeson.pair "message" $ lazyText $ coerce TLB.toLazyText message
+     ]
+  namespace = TL.intercalate ".". toList <$> NE.nonEmpty
+     [ TL.fromStrict tm
+     | Segment tm <- toList attributes
+     ]
+  user_data = fold <$> NE.nonEmpty
+    [ pair key attributeValue
+    | Attr key attributeValue <- toList attributes
+    ]
+
+
diff --git a/src/Colog/Json/Internal/Structured.hs b/src/Colog/Json/Internal/Structured.hs
new file mode 100644
--- /dev/null
+++ b/src/Colog/Json/Internal/Structured.hs
@@ -0,0 +1,129 @@
+{-# LANGUAGE UnliftedFFITypes #-}
+{-# LANGUAGE MagicHash #-}
+{-# OPTIONS_HADDOCK not-home #-}
+-- |
+--
+-- Structure for tracing context.
+--
+-- We assume that each message ('Message') can be tagged with two types of values:
+--
+--    * @segment@ - path that tells where are we in the codebase.
+--    * @attrbibutes@ - additional key-value tags, where value is an arbitrary json object.
+-- 
+-- Segment is needed in a case if we want to apply differrent logging rules to the differrent
+-- parts of the codebase. For example we may way to log all the messages in the component one
+-- but not all the rest.
+--
+-- In addition each @Message@ provides some common fields:
+--
+--    * "thread" - id of the thread that emits message
+--    * "severity" - message severity
+--
+-- All messages in the same context share segment and attributes. So when exported to the log
+-- analytics systems it's easy to load all the information associated with it.
+--
+-- **Compatibility note** internal structure of the message may be changed in the future in case
+-- if it's proven that another implementation is faster or more memory efficient. However the
+-- higher level API is likely to be stable.
+module Colog.Json.Internal.Structured
+  ( -- * Log datastructure.
+    Structured(..)
+  , Message(..)
+  , LogStr(..)
+  , PushContext(..)
+    -- * Internals.
+  , Severity(..)
+  , encodeSeverity
+  , showLS
+  , ls
+  , sl
+  , mkThreadId
+  ) where
+
+import Control.Concurrent
+import Data.Aeson
+import Data.Aeson.Encoding as Aeson
+import Data.Sequence
+import Data.String
+import Data.String.Conv
+import qualified Data.Text as T
+import qualified Data.Text.Lazy.Builder as TLB
+import Foreign.C
+import GHC.Conc
+import GHC.Exts hiding (toList)
+
+-- | Part of the structured message.
+data Structured
+  = Segment T.Text -- ^ Part of the message that is associated this the context of code.
+  | Attr T.Text Encoding -- ^ Add attribute to the list.
+
+-- | Log message.
+data Message = Message
+  { message_severity :: Severity -- ^ Message severity.
+  , thread_id :: Int -- ^ Thread that emitted message.
+  , attributes :: Seq Structured -- ^ List of attributes associated with the context.
+  , message :: LogStr -- ^ Message to log.
+  }
+
+
+-- | Efficient message builder.
+newtype LogStr = LogStr TLB.Builder
+  deriving newtype IsString
+  deriving newtype Semigroup
+  deriving newtype Monoid
+
+-- | Logger severity.
+data Severity
+  = DebugS      -- ^ Debug level, intended for internal information
+  | InfoS       -- ^ Info level, that may be interesting to the user
+  | NoticeS     -- ^ Notice, information that
+  | WarningS    -- ^ Warning, information possible problem problem of some sort
+  | ErrorS      -- ^ Error, information about a problem
+  | CriticalS   -- ^ Critical error, intended for error that may break the system
+  | AlertS      -- ^ Critical error where immediate actions should be taken
+  | EmergencyS  -- ^ System wide emergency
+  deriving (Show, Bounded, Eq, Ord, Enum)
+
+-- | Convert severity into the one accepted by the loger.
+encodeSeverity :: Severity -> Aeson.Encoding
+{-# INLINE encodeSeverity #-}
+encodeSeverity DebugS     = Aeson.text "DEBUG"
+encodeSeverity InfoS      = Aeson.text "INFO"
+encodeSeverity NoticeS    = Aeson.text "NOTICE"
+encodeSeverity WarningS   = Aeson.text "WARNING"
+encodeSeverity ErrorS     = Aeson.text "ERROR"
+encodeSeverity CriticalS  = Aeson.text "CRITICAL"
+encodeSeverity AlertS     = Aeson.text "ALERT"
+encodeSeverity EmergencyS = Aeson.text "EMERGENCY"
+
+-- | Wrapper over the structured message builder.
+newtype PushContext = PushContext (Seq Structured -> Seq Structured)
+
+-- | "Simple logger" adds a key value to the context:
+--
+-- @sl "foo" 123@
+--
+-- Will add @"foo":123@ key pair to the current list of the attributes.
+-- Submitted value is stored with json encoding.
+sl :: ToJSON a => T.Text -> a -> PushContext
+sl label msg = PushContext \x ->
+  x |> Attr label (toEncoding msg)
+
+-- | Log any message.
+logStr :: StringConv a T.Text => a -> LogStr
+logStr t = LogStr (TLB.fromText $ toS t)
+
+-- | Convert message can be converted.
+ls :: StringConv a T.Text => a -> LogStr
+ls = logStr
+
+-- | Convert loggable value from any message that has show instance.
+showLS :: Show a => a -> LogStr
+showLS = ls . show
+
+-- | Helper function to get id of the thread.
+mkThreadId :: ThreadId -> Int
+{-# NOINLINE mkThreadId #-}
+mkThreadId (ThreadId tid) = fromIntegral (getThreadId tid)
+
+foreign import ccall unsafe "rts_getThreadId" getThreadId :: ThreadId# -> CInt
diff --git a/src/Colog/Json/Message.hs b/src/Colog/Json/Message.hs
new file mode 100644
--- /dev/null
+++ b/src/Colog/Json/Message.hs
@@ -0,0 +1,11 @@
+module Colog.Json.Message
+  ( -- * Message
+    LogStr
+  , ls
+  , showLS
+    -- * Context
+  , PushContext
+  , sl
+  ) where
+
+import Colog.Json.Internal.Structured as Internal
