]> git.immae.eu Git - github/fretlink/haskell-graylog.git/blame - src/Graylog/UDP.hs
Added readme, license, and light commenting.
[github/fretlink/haskell-graylog.git] / src / Graylog / UDP.hs
CommitLineData
d9a5d441 1-- | UDP Chunked support for sending messages to graylog.
15981d57 2module Graylog.UDP
c91dbdc0 3 ( sendLog
15981d57 4
2ff46fce 5 , module Export
15981d57
A
6 ) where
7
c91dbdc0 8import Data.Aeson
f82a8dfc
A
9import Data.ByteString.Builder
10import qualified Data.ByteString.Lazy as LBS
11import Data.Monoid
12import Data.Word
c91dbdc0 13import Network.Socket.ByteString.Lazy
f82a8dfc 14import System.Random
c91dbdc0
A
15
16import Graylog.Gelf as Export
17import Graylog.Types as Export
15981d57
A
18
19sendLog :: Graylog -> GELF -> IO ()
b23afe7b 20sendLog glog msg = do
f82a8dfc
A
21 cks <- chunky glog raw
22 mapM_ (send $ _graylogSocket glog) cks
c91dbdc0
A
23 where
24 raw = encode msg
2ff46fce 25
f82a8dfc
A
26chunky :: Graylog -> LBS.ByteString -> IO [LBS.ByteString]
27chunky glog raw = do
28 groupId <- randomIO
29 let groups = divide totalNum raw
30 return $ append groupId groups seqNums
31 where
32 magic = word8 0x1e <> word8 0x0f
33 seqNums = [0..] :: [Word8]
34 totalNum = if excess > 0 then count + 1 else count
35 (count, excess) = quotRem (LBS.length raw) gsize
36 hlen = 12
37 gsize = (fromIntegral (_graylogChunkSize glog)) - hlen
38
39 divide 0 dat = [dat]
40 divide num dat = let (pre, post) = LBS.splitAt gsize dat
41 in pre : divide (num - 1) post
b23afe7b 42
f82a8dfc
A
43 append _ [] _ = []
44 append _ _ [] = error "the impossible has happened."
45 append gid (g:gs) (s:ss) = (toLazyByteString
46 $ magic
47 <> word64BE gid
48 <> word8 s
49 <> word8 (fromIntegral totalNum)
50 <> lazyByteString g) : append gid gs ss