首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >简单Python Logger

简单Python Logger
EN

Code Review用户
提问于 2017-12-28 06:22:29
回答 1查看 843关注 0票数 5

这里是一个简单的Python记录器,我希望得到一些一般性的反馈。

功能:

  • 在用户运行程序的地方动态创建日志文件夹和文件。
  • 从单个程序创建多个日志的能力
  • 从时间戳到防止名称冲突的最新第二个名称日志

我知道可能有更好的选择,但我只是想修改一下这个概念!

谢谢!

logger.py:

代码语言:javascript
复制
#!/usr/bin/python
# -*- coding: utf-8 -*-

import datetime
import time
import os
import sys

# get user's current directory

directory = os.path.dirname(os.path.realpath(__file__)) + '/logs'


def createNewLog():

    # ensure log folder exists

    if not os.path.exists(directory):
        os.mkdir(directory)

    # get timestamp for naming the log

    timeInSeconds = time.time()
    timestamp = \
        datetime.datetime.fromtimestamp(timeInSeconds).strftime('%Y-%m-%d %H:%M:%S'
            )

    logFile = directory + '/' + timestamp + '.txt'
    mostRecentLog = directory + '/mostRecentLog.txt'

    # create log file and file with the log file's name

    with open(logFile, 'w') as log:
        with open(mostRecentLog, 'w') as recentLog:
            recentLog.write(timestamp)


def findMostRecentLog():

    # ensure logger has been intiated

    try:
        with open(directory + '/mostRecentLog.txt', 'r') as logFile:
            logName = logFile.read()
    except FileNotFoundError:

        print("Must initiate logger first!")
        sys.exit(1)

    return directory + '/' + logName + '.txt'


def log(comment):
    comment = str(comment)

    # write to log file retriving most recent log from corresponding file

    with open(findMostRecentLog(), 'a') as log:
        log.write(comment + '\n')
EN

回答 1

Code Review用户

回答已采纳

发布于 2017-12-28 11:29:54

如果您还不知道,我建议您使用匹林特来解析您的代码并进行自动反馈。事实上,我的一些笔记是从潘林特来的。

造型笔记:

  • 像var“目录”这样的常量名称需要大写样式的PEP8
  • 函数和变量名需要snake_case样式的PEP8
  • 函数需要docstring以及模块本身的PEP8

内联注释

代码语言:javascript
复制
#NOTE: 'from datetime import datetime' allows a shorter line below
import datetime
import time
import os
import sys

# get user's current directory

# NOTE: use os.path.join for concat filesystem paths for cross compatibility (also below)
directory = os.path.dirname(os.path.realpath(__file__)) + '/logs'


def createNewLog():

    # ensure log folder exists

    if not os.path.exists(directory):
        # NOTE: what if user has no permission to create files/directory in current directory? (also below)
        # HINT: give a way to choose where to store logs
        os.mkdir(directory)

    # get timestamp for naming the log

    timeInSeconds = time.time()
    # NOTE: fromtimestamp may raise an exception which is not not managed here
    timestamp = \
        datetime.datetime.fromtimestamp(timeInSeconds).strftime('%Y-%m-%d %H:%M:%S'
            )

    logFile = directory + '/' + timestamp + '.txt'
    mostRecentLog = directory + '/mostRecentLog.txt'

    # create log file and file with the log file's name

    # NOTE: redefining name 'log' (it's also a function name)
    # NOTE: this 'log' is not used. What it's that for?
    with open(logFile, 'w') as log:
        with open(mostRecentLog, 'w') as recentLog:
            recentLog.write(timestamp)


def findMostRecentLog():

    # ensure logger has been intiated

    try:
        with open(directory + '/mostRecentLog.txt', 'r') as logFile:
            logName = logFile.read()
    except FileNotFoundError:
        print("Must initiate logger first!")
        # NOTE: kind of rugh, I suggest returning an error and managing at caller level
        sys.exit(1)

    return directory + '/' + logName + '.txt'


def log(comment):
    # NOTE: why forcing the type?
    comment = str(comment)

    # write to log file retriving most recent log from corresponding file

    # NOTE: this dependency will make hard testing this function alone.
    with open(findMostRecentLog(), 'a') as log:
        log.write(comment + '\n')
票数 2
EN
页面原文内容由Code Review提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://codereview.stackexchange.com/questions/183761

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档