我正在用python开发一个REST服务,它部署在AWS上作为Lambda。最初,Cloud Watch CLI 上没有记录任何内容,因此我引入了瞭望塔。
以下是我的 logging.in 文件。
[loggers]
keys=root
[handlers]
keys=screen, WatchtowerHandler
[formatters]
keys=logfileformatter
[logger_root]
level=DEBUG
handlers=screen
[logger_xyz]
level=DEBUG
handlers=screen, WatchtowerHandler
qualname=xyz
[formatter_logfileformatter]
format=%(asctime)s %(name)-12s: %(levelname)s %(message)s
class=logging.Formatter
[handler_logfile]
class=handlers.RotatingFileHandler
level=NOTSET
args=('log/xyz.log','a',100000,100)
formatter=logfileformatter
[handler_screen]
class=StreamHandler
args = (sys.stdout)
formatter=logfileformatter
[handler_WatchtowerHandler]
class=watchtower.CloudWatchLogHandler
formatter=formatter
send_interval=1
args= ()
上述方法适用于记录配置文件。
LOG.info("dev config detected")
但无法从应用程序中的任何其他代码记录 LOG.info((。 特别是 REST 调用,而日志记录在任何地方都是一样的。
您可以使用Watchtower或Cloudwatch Handler
瞭望塔:https://github.com/kislyuk/watchtower
import watchtower, logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
logger.addHandler(watchtower.CloudWatchLogHandler())
logger.info("Hi")
logger.info(dict(foo="bar", details={}))
云监视处理程序:https://pypi.org/project/cloudwatch/
import logging
from cloudwatch import cloudwatch
#Create the logger
logger = logging.getLogger('my_logger')
#Create the formatter
formatter = logging.Formatter('%(asctime)s : %(levelname)s - %(message)s')
# ---- Create the Cloudwatch Handler ----
handler = cloudwatch.CloudwatchHandler('AWS_KEY_ID','AWS_SECRET_KEY','AWS_REGION','AWS_LOG_GROUP','AWS_LOG_STREAM')
#Pass the formater to the handler
handler.setFormatter(formatter)
#Set the level
logger.setLevel(logging.WARNING)
#Add the handler to the logger
logger.addHandler(handler)
#USE IT!
logger.warning("Watch out! Something happened!")