programing

Oracle에 연결할 로깅 핸들러를 생성하시겠습니까?

stoneblock 2023. 8. 17. 20:34

Oracle에 연결할 로깅 핸들러를 생성하시겠습니까?

따라서 지금 당장은 데이터베이스에 로그하는 데 사용할 Python 로깅 모듈의 확장을 만들고 구현해야 합니다.기본적으로 현재 임의의 잘못된 텍스트 파일에 기록되는 여러 Python 애플리케이션(모두 백그라운드에서 실행됨)이 있습니다.이는 특정 응용 프로그램이 실패했는지 여부를 확인하는 것을 거의 불가능하게 만듭니다.

제게 주어진 문제는 텍스트 파일에 대한 해당 로깅을 오라클 DB로 이동하는 것입니다.테이블은 이미 정의되어 있으며, 로그에 기록해야 하는 위치에 DB에 기록할 다른 로깅 핸들러를 추가하려고 합니다.

저는 python 2.5.4와 cx_Oracle을 사용하고 있으며 일반적으로 애플리케이션은 서비스/데몬 또는 스트레이트 애플리케이션으로 실행될 수 있습니다.

저는 주로 이것에 대해 가능한 가장 좋은 방법이 무엇인지 궁금합니다.몇 가지 질문:

  1. cx_Oracle에서 오류가 발생할 경우 이러한 오류를 어디에 기록해야 합니까?다운된 경우 로거를 기본 텍스트 파일로 되돌리는 것이 가장 좋을까요?

  2. 얼마 전에 우리는 사람들이 sys.stderr/stdout을 사용하도록 시행하기 시작했습니다.인쇄 대신 쓰기 때문에 최악의 경우 인쇄가 더 이상 사용되지 않는 문제가 발생하지 않습니다.수천 개의 sys.std 호출을 모두 로거에 직접 파이프로 연결하고 로거가 슬랙을 픽업하도록 하는 방법이 있습니까?

  3. 기록된 모든 메시지 후 스크립트가 자동으로 커밋을 수행해야 합니까?(1초에 수십 개가 될 것입니다.)

  4. 로깅 시스템에 새 핸들러를 구현하는 가장 좋은 방법은 무엇입니까?기본 처리기 클래스에서 상속하는 것이 가장 쉬운 것 같습니다.

어떤 아이디어나 제안이든 좋습니다.

  1. cx_Oracle에서 오류가 발생하면 텍스트 파일에 기록하는 것이 가장 좋습니다.
  2. sys.stdout 및 sys.stderr을 파일과 같은 개체로 리디렉션하여 기록된 내용을 로거에 기록할 수 있습니다.
  3. 저는 당신이 이것을 하지 않는 강력한 이유가 없는 한, 당신이 각 사건 후에 약속하기를 원한다고 생각합니다.또는 여러 이벤트를 버퍼링하여 한 번의 트랜잭션에 모두 기록할 수 있습니다.
  4. 아래는 mx를 사용하는 예제입니다.ODBC, 큰 문제 없이 cx_Oracle로 조정할 수 있습니다.Python DB-API 2.0과 호환되어야 한다고 생각합니다.

독립 실행형 Python 로깅 배포판(로그가 Python에 추가되기 전)은 http://www.red-dove.com/python_logging.html 에 있으며 Python의 로깅 패키지가 훨씬 최신이지만 독립 실행형 배포판에는 파생된 핸들러 클래스의 유용한 예제가 많이 있는 테스트 디렉터리가 포함되어 있습니다.

#!/usr/bin/env python
#
# Copyright 2001-2009 by Vinay Sajip. All Rights Reserved.
#
# Permission to use, copy, modify, and distribute this software and its
# documentation for any purpose and without fee is hereby granted,
# provided that the above copyright notice appear in all copies and that
# both that copyright notice and this permission notice appear in
# supporting documentation, and that the name of Vinay Sajip
# not be used in advertising or publicity pertaining to distribution
# of the software without specific, written prior permission.
# VINAY SAJIP DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
# ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL
# VINAY SAJIP BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
# ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
# IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#
# This file is part of the standalone Python logging distribution. See
# http://www.red-dove.com/python_logging.html
#
"""
A test harness for the logging module. An example handler - DBHandler -
which writes to an Python DB API 2.0 data source. You'll need to set this
source up before you run the test.

Copyright (C) 2001-2009 Vinay Sajip. All Rights Reserved.
"""
import sys, string, time, logging

class DBHandler(logging.Handler):
    def __init__(self, dsn, uid='', pwd=''):
        logging.Handler.__init__(self)
        import mx.ODBC.Windows
        self.dsn = dsn
        self.uid = uid
        self.pwd = pwd
        self.conn = mx.ODBC.Windows.connect(self.dsn, self.uid, self.pwd)
        self.SQL = """INSERT INTO Events (
                        Created,
                        RelativeCreated,
                        Name,
                        LogLevel,
                        LevelText,
                        Message,
                        Filename,
                        Pathname,
                        Lineno,
                        Milliseconds,
                        Exception,
                        Thread
                   )
                   VALUES (
                        %(dbtime)s,
                        %(relativeCreated)d,
                        '%(name)s',
                        %(levelno)d,
                        '%(levelname)s',
                        '%(message)s',
                        '%(filename)s',
                        '%(pathname)s',
                        %(lineno)d,
                        %(msecs)d,
                        '%(exc_text)s',
                        '%(thread)s'
                   );
                   """
        self.cursor = self.conn.cursor()

    def formatDBTime(self, record):
        record.dbtime = time.strftime("#%m/%d/%Y#", time.localtime(record.created))

    def emit(self, record):
        try:
            #use default formatting
            self.format(record)
            #now set the database time up
            self.formatDBTime(record)
            if record.exc_info:
                record.exc_text = logging._defaultFormatter.formatException(record.exc_info)
            else:
                record.exc_text = ""
            sql = self.SQL % record.__dict__
            self.cursor.execute(sql)
            self.conn.commit()
        except:
            import traceback
            ei = sys.exc_info()
            traceback.print_exception(ei[0], ei[1], ei[2], None, sys.stderr)
            del ei

    def close(self):
        self.cursor.close()
        self.conn.close()
        logging.Handler.close(self)

dh = DBHandler('Logging')
logger = logging.getLogger("")
logger.setLevel(logging.DEBUG)
logger.addHandler(dh)
logger.info("Jackdaws love my big %s of %s", "sphinx", "quartz")
logger.debug("Pack my %s with five dozen %s", "box", "liquor jugs")
try:
    import math
    math.exp(1000)
except:
    logger.exception("Problem with %s", "math.exp")

언급URL : https://stackoverflow.com/questions/935930/creating-a-logging-handler-to-connect-to-oracle