skip to Main Content

I am currently struggling to set up some basic logging in AWS Lambda. I have a function created from a container image where the main.py file looks like this:

import os

def lambda_handler(event, context):
    log_file = "/tmp/application.log"
    
    if os.path.exists(log_file):
        with open(log_file, "r") as f:
            file = f.read()
    else:
        file = "File does not exist"
    return {
        "statusCode": 200,
        "body": file
    }

The logging configuration is created in another file, logging_config.py:

import logging

LOG_FILE = "/tmp/application.log"

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s - %(levelname)s - %(message)s",
    handlers=[
        logging.FileHandler(LOG_FILE),
        logging.StreamHandler(),
    ]
)

logger = logging.getLogger("my-logger")

The logger variable is then imported into other modules that should log on various levels (info, debug, error). However, I am not able to see the logs anywhere, nor do they get redirected to the /tmp/application.log file. When the function finishes executing, it returns:

{
  "statusCode": 200,
  "body": ""
}

So I am assuming that the log file gets created because the body is empty, but not populated with anything.
What I am missing? Thanks.

I tried the solution above but the logs were not redirected to the log file.

2

Answers


  1. Chosen as BEST ANSWER

    Thanks for the suggestions. In the end, I moved away from the idea of configuring my own logging, and instead just used print statements and fetch the logs from Cloudwatch right before the function exits.


  2. The easiest way to do logging is to simply print() information.

    When running the Lambda function in the management console, messages will appear after using the Test function.

    Also, any executions of the Lambda function will send these messages to CloudWatch Logs, which can be accessed via the Monitoring tab in the Lambda console. It will include information about when the function started and stopped, plus and messages that were printed during execution.

    This way, you not need to change what is returned by the function itself.

    Given that the Lambda environment is only temporary, this approach is much better than attempting to handle files on the local operating system, which can disappear after the function stops running.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search