Azure函数-使用日志记录登录到文件并返回文件内容以响应http请求?

8yoxcaq7  于 2023-04-12  发布在  其他
关注(0)|答案(1)|浏览(90)

我需要用python写一个azure函数(基于http的触发器)。(注意-函数是从blob存储中以zip部署的方式运行的。)
函数应使用日志记录将消息、错误和警告记录到特定日志文件中。
在最后我想读这个日志文件,并返回它作为httpd。响应?

Here is my code.

import os
import os.path
import azure.functions as func
import logging as cslog
import random
import time

app = func.FunctionApp()

@app.function_name(name="HttpTrigger1")
@app.route(route="hello")
def test_function(req: func.HttpRequest) -> func.HttpResponse:
    log_file = os.path.join(os.environ['TMP'], str(random.randint(1, 100)) + ".app.log")

    cslog.basicConfig(filename=log_file, filemode='w',
                      format='%(asctime)s - %(process)d - %(levelname)s - %(message)s', datefmt='%d-%b-%Y %H:%M:%S')

    cslog.warning('No1. This will get logged to a file')
    cslog.warning('No2. This will get logged to a file')
    cslog.warning('No3. This will get logged to a file')
    cslog.warning('No4. This will get logged to a file')
    cslog.info(os.getcwd())
    check_file = os.path.isfile(log_file)
    cslog.info(check_file)

    with open(log_file) as f:
        content_text = "\n"
        content = f.readlines()
        for line in content:
            content_text = content_text + str(line)

    return func.HttpResponse(content_text)

当我运行函数时,它给我错误,日志文件不存在?为什么会发生?

bbmckpt7

bbmckpt71#

当我运行函数时,它给我错误,日志文件不存在?为什么会发生?
当函数代码无法在您的目录中找到日志文件以将日志写入其中时,会发生错误。您可以在函数zip文件夹中手动创建日志文件,或者在函数代码中动态将日志写入该文件,并使用以下代码在HTTP响应中返回文件内容:-

我的init.py:-

import os
import azure.functions as func
import logging as cslog

# app = func.FunctionApp()

# @app.function_name(name="HttpTrigger1")
# @app.route(route="hello")
def main(req: func.HttpRequest) -> func.HttpResponse:
    log_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), "app.log")

    cslog.basicConfig(filename=log_file, filemode='a',
                      format='%(asctime)s - %(process)d - %(levelname)s - %(message)s', datefmt='%d-%b-%Y %H:%M:%S')

    cslog.warning('No1. This will get logged to a file')
    cslog.warning('No2. This will get logged to a file')
    cslog.warning('No3. This will get logged to a file')
    cslog.warning('No4. This will get logged to a file')

    try:
        with open(log_file, mode='a') as f:
            f.write('No1. This will get logged to a file\n')
            f.write('No2. This will get logged to a file\n')
            f.write('No3. This will get logged to a file\n')
            f.write('No4. This will get logged to a file\n')
    except Exception as e:
        cslog.error(f"Error writing to log file: {str(e)}")

    try:
        with open(log_file) as f:
            content_text = "\n"
            content = f.readlines()
            for line in content:
                content_text = content_text + str(line)
    except FileNotFoundError:
        content_text = "Log file not found"

    return func.HttpResponse(content_text)

输出:-

浏览器HTTP响应:-

app.log文件内容:-

相关问题