Code4Bread
Code4Bread

Reputation: 193

Python Logging in Docker

I am test running python Script in Docker Container on Ubuntu Web Server. I am trying to find the Log file generated by Python Logger Module. Below is my Python Script

import time
import logging



def main():

    logging.basicConfig(filename="error.log", level=logging.DEBUG)

    start_time = time.time()
    logging.debug("Program starts running at %d", start_time)


    i = 0
    while i < 1000:
        print(i)
        i += 1

    while_time = time.time() - start_time

    logging.debug("Program ends running at %d", while_time)

    start_time = time.time()

    logging.debug("Program starts running at %d", start_time)

    for x in range(0, 100):
        print(x)

    if_time = time.time() - start_time

    print('While took - %s Seconds' % while_time )
    print('If took - %s Seconds' % if_time )

    logging.debug("Program ends running at %d", start_time)


main()

I have searched and found that Docker file produces Log file in json format in /var/lib/docker/container/{con_id}/{con_id}.log This log file only includes the stdout and I cannot find the Log file generated by Python. Is there any way to retrieve the file.

Upvotes: 7

Views: 24647

Answers (1)

Zeinab Abbasimazar
Zeinab Abbasimazar

Reputation: 10439

You have specified file 'error.log' in command logging.basicConfig(filename="error.log", level=logging.DEBUG) for logger to put your logs into. This file is located inside your container and since containers are stateless, you have to mount the log file somewhere in your local machine in order to have access after powering off your container. You can read this for more information.

BTW, if you want to access the log file while it's already up, you can use exec option of the docker to make an interactive shell through the container and find the logs:

docker exec -it ${container_name}

This documentation will helpful for exec commandline option.

Upvotes: 10

Related Questions