Skip to content

Commit

Permalink
sa logging minor improvements
Browse files Browse the repository at this point in the history
  • Loading branch information
ali96343 committed Sep 1, 2023
1 parent 76247ae commit c4befed
Showing 1 changed file with 114 additions and 34 deletions.
148 changes: 114 additions & 34 deletions py4web/server_adapters.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import logging
import os
import sys
import ssl

from ombott.server_adapters import ServerAdapter
Expand All @@ -16,6 +17,16 @@
"rocketServer",
] + wsservers_list

# ---------------------- utils -----------------------------------------------

# export PY4WEB_LOGS=/tmp # export PY4WEB_LOGS=
def get_log_file():
LOG_DIR = os.environ.get("PY4WEB_LOGS", None)
LOG_FILE = os.path.join (LOG_DIR, 'server-py4web.log') if LOG_DIR else None
if LOG_FILE:
print(f"log_file: {LOG_FILE}")
return LOG_FILE


def check_level(level):

Expand Down Expand Up @@ -44,26 +55,46 @@ def check_level(level):
)


def logging_conf(level, log_file="server-py4web.log"):
def logging_conf(level=logging.WARN, logger_name=__name__):

# export PY4WEB_LOGS=/tmp # set log_file directory
LOG_FILE = get_log_file()
log_to = dict()

log_dir = os.environ.get("PY4WEB_LOGS", None)
if LOG_FILE:

log_param = {
"format":"%(threadName)s | %(message)s",
"level":check_level(level),
}

if log_dir:
h = logging.FileHandler(
os.path.join( log_dir, log_file),
if sys.version_info >= (3, 9):
log_to["filename" ] = LOG_FILE
log_to["filemode" ] = "w"
log_to["encoding"] = "utf-8"
else: # sys.version_info < (3, 9)
h = logging.FileHandler(
LOG_FILE,
mode = "w",
encoding = "utf-8"
)
log_param.update( {"handlers": [h]} )
log_to.update( {"handlers": [h]} )


logging.basicConfig(**log_param)
short_msg = "%(message)s > %(threadName)s > %(asctime)s.%(msecs)03d"
#long_msg = short_msg + " > %(funcName)s > %(filename)s:%(lineno)d > %(levelname)s"

time_msg = '%H:%M:%S'
#date_time_msg = '%Y-%m-%d %H:%M:%S'
logging.basicConfig(
format=short_msg,
datefmt=time_msg,
level=check_level(level),
**log_to,
)

logger_name = "SA:" + logger_name
log = logging.getLogger(logger_name)
log.propagate = True
log.info( f'info start logger {logger_name}' )
log.warn( f'warn start logger {logger_name}' )
log.debug( f'debug start logger {logger_name}' )
return log


def get_workers(opts, default=10):
Expand All @@ -72,9 +103,10 @@ def get_workers(opts, default=10):
except KeyError:
return default

# ---------------------- servers -----------------------------------------------

def gevent():
# gevent version 22.10.2
# gevent version 23.7.0

import threading

Expand All @@ -91,22 +123,21 @@ def gevent():

class GeventServer(ServerAdapter):
def run(self, handler):
LOG_FILE = get_log_file()

logger = "default" # not None - from gevent doc
if not self.quiet:
logger = "default"

logger = logging.getLogger("gevent")
log_dir = os.environ.get("PY4WEB_LOGS", None)
if not self.quiet:
logger = logging.getLogger("SA:gevent")
fh = (
logging.FileHandler(None)
if not log_dir
else (
logging.FileHandler(os.path.join(log_dir, "server-py4web.log"))
)
logging.FileHandler()
if not LOG_FILE
else logging.FileHandler(LOG_FILE, mode='w')
)
logger.setLevel(check_level(self.options["logging_level"]))
logger.addHandler(fh)
logger.addHandler(logging.StreamHandler())
#logger.addHandler(logging.StreamHandler())
logger.propagate = True

certfile = self.options.get("certfile", None)

Expand Down Expand Up @@ -154,12 +185,13 @@ def geventWebSocketServer():

class GeventWebSocketServer(ServerAdapter):
def run(self, handler):
logger = "default" # not None !! from gevent doc
logger = "default"

if not self.quiet:
logging_conf(
self.options["logging_level"],
logger = logging_conf(
self.options["logging_level"], "gevent-ws",
)
logger = logging.getLogger("gevent-ws")


certfile = self.options.get("certfile", None)

Expand Down Expand Up @@ -198,11 +230,9 @@ class WSGIRefThreadingServer(ServerAdapter):
def run(self, app):

if not self.quiet:

logging_conf(
self.options["logging_level"],
self.log = logging_conf(
self.options["logging_level"], "wsgiref",
)
self.log = logging.getLogger("WSGIRef")

self_run = self # used in internal classes to access options and logger

Expand Down Expand Up @@ -277,7 +307,7 @@ def log_message(self, format, *args):
)
self_run.log.info(msg)

handler_cls = self.options.get("handler_class", LogHandler)
#handler_cls = self.options.get("handler_class", LogHandler)
server_cls = Server

if ":" in self.host: # Fix wsgiref for IPv6 addresses.
Expand All @@ -288,7 +318,7 @@ class ServerClass(Server):

server_cls = ServerClass

srv = make_server(self.host, self.port, app, server_cls, handler_cls)
srv = make_server(self.host, self.port, app, server_cls, LogHandler ) # handler_cls)
srv.serve_forever()

return WSGIRefThreadingServer
Expand Down Expand Up @@ -327,3 +357,53 @@ def run(self, app):
server.start()

return RocketServer


"""
# how to write to server-adapters.log from controllers.py
# cp -a _scaffold test-salog
import sys
import logging
from .common import logger
from .settings import APP_NAME
from threading import Lock
_sa_lock = Lock()
_srv_log=None
def log_info(mess, dbg=True, ):
def salog(pat='SA:'):
global _srv_log, _sa_lock
if _srv_log: # and isinstance( _srv_log, logging.Logger ):
return _srv_log
hs= [e for e in logging.root.manager.loggerDict if e.startswith(pat) ]
if len(hs) == 0:
return logger
_sa_lock.acquire()
_srv_log = logging.getLogger(hs[0])
_sa_lock.release()
return _srv_log
dbg and salog().info(str(mess))
log_warn=log_info
log_debug=log_info
log_warn('0'* 30 + ' ' +APP_NAME)
@action("index")
@action.uses("index.html", auth, T)
def index():
log_warn('7'* 30 + ' ' +APP_NAME)
log_info('9'* 30 + ' ' +APP_NAME)
user = auth.get_user()
message = T("Hello {first_name}").format(**user) if user else T("Hello")
actions = {"allowed_actions": auth.param.allowed_actions}
return dict(message=message, actions=actions)
"""

0 comments on commit c4befed

Please sign in to comment.