Python logging and dump to json

The ** logging ** package that comes standard is easy to use, but it's reasonable. I feel like the file handler isn't killed until the script dies. The following is a simple example of personally unexpected behavior. (Maybe this is the correct behavior ... Tell me more!)

sample_logging.py


from datetime import datetime as dt
import os, logging
def main():
  for i in xrange(1,6):
    log = logging.getLogger()
    
    #i-th iteration directory
    dir_name = "dir_{0}".format(i)
    os.makedirs(dir_name)

    #Log file (want to create) for i-th repeat directory
    log_file_name = "{0}/lg_index{1}.log".format(dir_name, i)
    logging.basicConfig(level = logging.INFO,\
                        filename = log_file_name,\
                        format = "[%(name)s: %(levelname)s @ %(asctime)s] %(message)s")

    # log
    log.info('hoge')
    log.info('foo')
    log.info(dt.now().strftime('%Y%m%d%H%M%S))

As a feeling, in each directory of dir_1, dir_2, ..., dir_5 I wanted to write a log when I did something, but when I do this In the log file (dir_1 / lg_index1.log "of dir_1 where logging was set first All info (because level = logging.INFO in this case) is written out. (This usage may not be correct / cool in the first place.)

Countermeasure 1 (Handling file handlers / Isn't it too beautiful?)

I referred to this (* I've been squeezed by copying)

sample_logging_new.py


from datetime import datetime as dt
import os, logging
def main():
  for i in xrange(1,6):
    log = logging.getLogger()
    
    #i-th iteration directory
    dir_name = "dir_{0}".format(i)
    os.makedirs(dir_name)

    #Log file (want to create) for i-th repeat directory
    log_file_name = "{0}/lg_index{1}.log".format(dir_name, i)
    log.setLevel(logging.INFO)
    fh = logging.FileHandler(filename = log_file_name)
    formatter = logging.Formatter(
        fmt='"[%(name)s: %(levelname)s @ %(asctime)s] %(message)s"',
        datefmt='%Y-%m-%d %H:%M:%S')
    fh.setFormatter(formatter)
    log.addHandler(fh)    

    # log
    log.info('hoge')
    log.info('foo')
    log.info(dt.now().strftime('%Y%m%d%H%M%S))

    # close file handler
    log.removeHandler(fh)
    del log, fh

Countermeasure 2 (If you use a file handler anyway, write it out directly)

@shima__shima taught me.

sample_logging_json.py


from datetime import datetime as dt
import os, json
def main():
  for i in xrange(1,6):
    #i-th iteration directory
    info = {} #Dictionary to put data
    dir_name = "dir_{0}".format(i)
    os.makedirs(dir_name)

    #Log file (want to create) for i-th repeat directory
    log_file_name = "{0}/lg_index{1}.log".format(dir_name, i)
    info['hoge'] = 0
    info['foo'] = 0
    info['bar'] = dt.now().strftime('%Y%m%d%H%M%S)
    
    #json file export
    with open(log_file_name, 'w') as f:
        json.dump(info, f)

I thought that I didn't have to use logging if I just wanted to write out information (parameters, time, etc.).

Recommended Posts

Python logging and dump to json
Python 3.6 on Windows ... and to Xamarin.
[Introduction to Python] How to parse JSON
JSON encoding and decoding with python
Python #JSON
Selenium and python to open google
Python Logging
How to package and distribute Python scripts
Try logging in to qiita with Python
From Python to using MeCab (and CaboCha)
How to install and use pandas_datareader [Python]
Convert Excel data to JSON with python
Fractal to make and play with Python
Porting and modifying doublet-solver from python2 to python3.
Read Python csv and export to txt
Read and write JSON files in Python
Dump SQLite3 data and migrate to MySQL
Dump BigQuery tables to GCS using Python
python: How to use locals () and globals ()
[Python] How to calculate MAE and RMSE
How to use Python zip and enumerate
Compress python data and write to sqlite
How to use is and == in Python
"Backport" to python 2
Scraping tabelog with python and outputting to CSV
MessagePack-Try to link Java and Python with RPC
How to generate permutations in Python and C ++
[Introduction to Python3 Day 12] Chapter 6 Objects and Classes (6.3-6.15)
Image characters and post to slack (python slackbot)
Read JSON with Python and output as CSV
How to create a JSON file in Python
[Introduction to Python3 Day 22] Chapter 11 Concurrency and Networking (11.1 to 11.3)
Reading and writing CSV and JSON files in Python
Send messages to Skype and Chatwork in Python
[Introduction to Python] How to handle JSON format data
[Introduction to Udemy Python3 + Application] 64. Namespace and Scope
[Introduction to Python3 Day 11] Chapter 6 Objects and Classes (6.1-6.2)
Output python log to both console and file
[Python3] Read and write with datetime isoformat with json
POST JSON in Python and receive it in PHP
Batch conversion of Excel files to JSON [Python]
List of Python code to move and remember
To represent date, time, time, and seconds in Python
How to plot autocorrelation and partial autocorrelation in python
[python] Compress and decompress
Convert timezoned date and time to Unixtime in Python2.7
Parse a JSON string written to a file in Python
Python and numpy tips
[Python] Convert decimal numbers to binary numbers, octal numbers, and hexadecimal numbers
[Python] [Django] How to use ChoiceField and how to add options
[Python] pip and wheel
[Python] Use JSON with Python
How to install Python
[Python] Convert general-purpose container and class to each other
Changes from Python 3.0 to Python 3.5
Batch design and python
[Python3] Connection to Oracle Database and SQL execution [cx_Oracle]
Changes from Python 2 to Python 3.0
Python iterators and generators
I want to handle optimization with python and cplex
Handling json in python