Use default python logger

This commit is contained in:
Sleepy Monax 2023-05-26 21:41:41 +01:00 committed by Sleepy Monax
parent 571cfe4585
commit 24d86e7eab
7 changed files with 33 additions and 54 deletions

View file

@ -1,4 +1,5 @@
import sys import sys
import logging
from os.path import isdir from os.path import isdir
from osdk import const, shell from osdk import const, shell
@ -9,19 +10,20 @@ import osdk.vt100 as vt100
def main() -> int: def main() -> int:
logging.basicConfig(
level=logging.INFO,
format=f"{vt100.CYAN}%(asctime)s{vt100.RESET} {vt100.YELLOW}%(levelname)s{vt100.RESET} %(name)s: %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)
a = parse(sys.argv[1:]) a = parse(sys.argv[1:])
if not a.consumeOpt("verbose", False):
if not isdir(const.OSDK_DIR):
shell.mkdir(const.OSDK_DIR)
sys.stderr = open(f"{const.OSDK_DIR}/osdk.log", "w")
try: try:
loadAll() loadAll()
exec(a) exec(a)
return 0 return 0
except Exception as e: except Exception as e:
print(f"{vt100.RED}{e}{vt100.RESET}") logging.error(f"{vt100.RED}{e}{vt100.RESET}")
print() print()
usage() usage()

View file

@ -1,13 +1,13 @@
import os import os
import logging
from typing import TextIO from typing import TextIO
from osdk.model import Props from osdk.model import Props
from osdk.ninja import Writer from osdk.ninja import Writer
from osdk.logger import Logger
from osdk.context import ComponentInstance, Context, contextFor from osdk.context import ComponentInstance, Context, contextFor
from osdk import shell, rules from osdk import shell, rules
logger = Logger("builder") logger = logging.getLogger(__name__)
def gen(out: TextIO, context: Context): def gen(out: TextIO, context: Context):

View file

@ -2,13 +2,12 @@ from typing import cast, Protocol, Iterable
from itertools import chain from itertools import chain
from pathlib import Path from pathlib import Path
import os import os
import logging
from osdk.model import ProjectManifest, TargetManifest, ComponentManifest, Props, Type, Tool, Tools from osdk.model import ProjectManifest, TargetManifest, ComponentManifest, Props, Type, Tool, Tools
from osdk.logger import Logger
from osdk import const, shell, jexpr, utils, rules, mixins from osdk import const, shell, jexpr, utils, rules, mixins
logger = Logger("context") logger = logging.getLogger(__name__)
class IContext(Protocol): class IContext(Protocol):
@ -238,7 +237,7 @@ def contextFor(targetSpec: str, props: Props = {}) -> Context:
if targetSpec in context: if targetSpec in context:
return context[targetSpec] return context[targetSpec]
logger.log(f"Loading context for '{targetSpec}'") logger.info(f"Loading context for '{targetSpec}'")
targetEls = targetSpec.split(":") targetEls = targetSpec.split(":")

View file

@ -1,21 +0,0 @@
import sys
import osdk.vt100 as vt100
class Logger:
name: str
def __init__(self, name: str):
self.name = name
def log(self, message: str):
print(
f"{vt100.CYAN}[{self.name}]{vt100.RESET} {message}", file=sys.stderr)
def warn(self, message: str):
print(
f"{vt100.YELLOW}[{self.name}]{vt100.RESET} {message}", file=sys.stderr)
def error(self, message: str):
print(
f"{vt100.RED}[{self.name}]{vt100.RESET} {message}", file=sys.stderr)

View file

@ -1,12 +1,12 @@
import os import os
from enum import Enum from enum import Enum
from typing import Any from typing import Any
import logging
from osdk.jexpr import Json from osdk.jexpr import Json
from osdk.logger import Logger
logger = Logger("model") logger = logging.getLogger(__name__)
Props = dict[str, Any] Props = dict[str, Any]
@ -259,13 +259,13 @@ class ComponentManifest(Manifest):
def isEnabled(self, target: TargetManifest) -> tuple[bool, str]: def isEnabled(self, target: TargetManifest) -> tuple[bool, str]:
for k, v in self.enableIf.items(): for k, v in self.enableIf.items():
if not k in target.props: if not k in target.props:
logger.log( logger.info(
f"Component {self.id} disabled by missing {k} in target") f"Component {self.id} disabled by missing {k} in target")
return False, f"Missing props '{k}' in target" return False, f"Missing props '{k}' in target"
if not target.props[k] in v: if not target.props[k] in v:
vStrs = [f"'{str(x)}'" for x in v] vStrs = [f"'{str(x)}'" for x in v]
logger.log( logger.info(
f"Component {self.id} disabled by {k}={target.props[k]} not in {v}") f"Component {self.id} disabled by {k}={target.props[k]} not in {v}")
return False, f"Props missmatch for '{k}': Got '{target.props[k]}' but expected {', '.join(vStrs)}" return False, f"Props missmatch for '{k}': Got '{target.props[k]}' but expected {', '.join(vStrs)}"

View file

@ -1,14 +1,13 @@
import os import os
import logging
import importlib.util as importlib import importlib.util as importlib
from osdk.logger import Logger
from osdk.shell import readdir from osdk.shell import readdir
logger = Logger("plugins") logger = logging.getLogger(__name__)
def load(path: str): def load(path: str):
logger.log(f"Loading plugin {path}") logger.info(f"Loading plugin {path}")
spec = importlib.spec_from_file_location("plugin", path) spec = importlib.spec_from_file_location("plugin", path)
if not spec or not spec.loader: if not spec or not spec.loader:
@ -20,7 +19,7 @@ def load(path: str):
def loadAll(): def loadAll():
logger.log("Loading plugins...") logger.info("Loading plugins...")
for files in readdir(os.path.join("meta", "plugins")): for files in readdir(os.path.join("meta", "plugins")):
if files.endswith(".py"): if files.endswith(".py"):
plugin = load(os.path.join("meta", "plugins", files)) plugin = load(os.path.join("meta", "plugins", files))

View file

@ -8,11 +8,11 @@ import re
import shutil import shutil
import fnmatch import fnmatch
import platform import platform
import logging
from osdk.logger import Logger
from osdk import const from osdk import const
logger = Logger("shell") logger = logging.getLogger(__name__)
class Uname: class Uname:
@ -45,7 +45,7 @@ def sha256sum(path: str) -> str:
def find(path: str | list[str], wildcards: list[str] = [], recusive: bool = True) -> list[str]: def find(path: str | list[str], wildcards: list[str] = [], recusive: bool = True) -> list[str]:
logger.log(f"Looking for files in {path} matching {wildcards}") logger.info(f"Looking for files in {path} matching {wildcards}")
result: list[str] = [] result: list[str] = []
@ -81,7 +81,7 @@ def find(path: str | list[str], wildcards: list[str] = [], recusive: bool = True
def mkdir(path: str) -> str: def mkdir(path: str) -> str:
logger.log(f"Creating directory {path}") logger.info(f"Creating directory {path}")
try: try:
os.makedirs(path) os.makedirs(path)
@ -92,7 +92,7 @@ def mkdir(path: str) -> str:
def rmrf(path: str) -> bool: def rmrf(path: str) -> bool:
logger.log(f"Removing directory {path}") logger.info(f"Removing directory {path}")
if not os.path.exists(path): if not os.path.exists(path):
return False return False
@ -111,7 +111,7 @@ def wget(url: str, path: str | None = None) -> str:
if os.path.exists(path): if os.path.exists(path):
return path return path
logger.log(f"Downloading {url} to {path}") logger.info(f"Downloading {url} to {path}")
r = requests.get(url, stream=True) r = requests.get(url, stream=True)
r.raise_for_status() r.raise_for_status()
@ -125,7 +125,7 @@ def wget(url: str, path: str | None = None) -> str:
def exec(*args: str): def exec(*args: str):
logger.log(f"Executing {args}") logger.info(f"Executing {args}")
try: try:
proc = subprocess.run(args) proc = subprocess.run(args)
@ -147,7 +147,7 @@ def exec(*args: str):
def popen(*args: str) -> str: def popen(*args: str) -> str:
logger.log(f"Executing {args}") logger.info(f"Executing {args}")
try: try:
proc = subprocess.run(args, stdout=subprocess.PIPE, stderr=sys.stderr) proc = subprocess.run(args, stdout=subprocess.PIPE, stderr=sys.stderr)
@ -165,7 +165,7 @@ def popen(*args: str) -> str:
def readdir(path: str) -> list[str]: def readdir(path: str) -> list[str]:
logger.log(f"Reading directory {path}") logger.info(f"Reading directory {path}")
try: try:
return os.listdir(path) return os.listdir(path)
@ -174,13 +174,13 @@ def readdir(path: str) -> list[str]:
def cp(src: str, dst: str): def cp(src: str, dst: str):
logger.log(f"Copying {src} to {dst}") logger.info(f"Copying {src} to {dst}")
shutil.copy(src, dst) shutil.copy(src, dst)
def cpTree(src: str, dst: str): def cpTree(src: str, dst: str):
logger.log(f"Copying {src} to {dst}") logger.info(f"Copying {src} to {dst}")
shutil.copytree(src, dst, dirs_exist_ok=True) shutil.copytree(src, dst, dirs_exist_ok=True)
@ -203,7 +203,7 @@ def latest(cmd: str) -> str:
if cmd in LATEST_CACHE: if cmd in LATEST_CACHE:
return LATEST_CACHE[cmd] return LATEST_CACHE[cmd]
logger.log(f"Finding latest version of {cmd}") logger.info(f"Finding latest version of {cmd}")
regex = re.compile(r"^" + re.escape(cmd) + r"(-.[0-9]+)?(\.exe)?$") regex = re.compile(r"^" + re.escape(cmd) + r"(-.[0-9]+)?(\.exe)?$")
@ -220,7 +220,7 @@ def latest(cmd: str) -> str:
versions.sort() versions.sort()
chosen = versions[-1] chosen = versions[-1]
logger.log(f"Chosen {chosen} as latest version of {cmd}") logger.info(f"Chosen {chosen} as latest version of {cmd}")
LATEST_CACHE[cmd] = chosen LATEST_CACHE[cmd] = chosen