Skip to content

Commit

Permalink
initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
sfujiwara committed Aug 31, 2016
1 parent fa5061a commit f3d9f64
Show file tree
Hide file tree
Showing 3 changed files with 70 additions and 0 deletions.
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
.idea
DS_Store
*.pyc
*.log
*.json
36 changes: 36 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# gjhandler

gjhandler is a simple log handler which generates JSON files for Cloud Logging and google-fluentd.

## Example

```python
import logging
import gjhandler

logger = logging.getLogger("gj_logger")
logger.setLevel(logging.DEBUG)
logger.addHandler(gjhandler.GoogleJsonHandler(filename="log_test.json"))

logger.info("this is info")
logger.error("this is error")
```

### Resulting Outputs

```json
{"timestamp": {"seconds": 1472657255, "nanos": 154423952}, "message": "this is info", "severity": "INFO", "thread": 140735257141248}
{"timestamp": {"seconds": 1472657255, "nanos": 155013084}, "message": "this is error", "severity": "ERROR", "thread": 140735257141248}
```

## Setting for google-fluentd

```xml
<source>
type tail
format json
path /var/log/python/*.log,/var/log/python/*.json
read_from_head true
tag python
</source>
```
29 changes: 29 additions & 0 deletions gjhandler.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# -*- coding: utf-8 -*-

import json
import logging.handlers
import math


class GoogleJsonHandler(logging.handlers.RotatingFileHandler):

def __init__(self, filename):
super(GoogleJsonHandler, self).__init__(
filename,
maxBytes=8*1024*1024,
backupCount=5
)

def format(self, record):
message = super(GoogleJsonHandler, self).format(record)
subsecond, second = math.modf(record.created)
payload = {
"message": message,
"timestamp": {
"seconds": int(second),
"nanos": int(subsecond * 1e9)
},
"thread": record.thread,
"severity": record.levelname,
}
return json.dumps(payload, ensure_ascii=False)

0 comments on commit f3d9f64

Please sign in to comment.