我需要用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)
当我运行函数时,它给我错误,日志文件不存在?为什么会发生?
1条答案
按热度按时间bbmckpt71#
当我运行函数时,它给我错误,日志文件不存在?为什么会发生?
当函数代码无法在您的目录中找到日志文件以将日志写入其中时,会发生错误。您可以在函数zip文件夹中手动创建日志文件,或者在函数代码中动态将日志写入该文件,并使用以下代码在HTTP响应中返回文件内容:-
我的init.py:-
输出:-
浏览器HTTP响应:-
app.log文件内容:-