python异常消息捕获
import ftplib
import urllib2
import os
import logging
logger = logging.getLogger('ftpuploader')
hdlr = logging.FileHandler('ftplog.log')
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
logger.setLevel(logging.INFO)
FTPADDR = "some ftp address"
def upload_to_ftp(con, filepath):
try:
f = open(filepath,'rb') # file to send
con.storbinary('STOR '+ filepath, f) # Send the file
f.close() # Close file and FTP
logger.info('File successfully uploaded to '+ FTPADDR)
except, e:
logger.error('Failed to upload to ftp: '+ str(e))
这似乎不起作用,我收到语法错误,将所有类型的异常记录到文件的正确方法是什么
import ftplib
import urllib2
import os
import logging
logger = logging.getLogger('ftpuploader')
hdlr = logging.FileHandler('ftplog.log')
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
logger.setLevel(logging.INFO)
FTPADDR = "some ftp address"
def upload_to_ftp(con, filepath):
try:
f = open(filepath,'rb') # file to send
con.storbinary('STOR '+ filepath, f) # Send the file
f.close() # Close file and FTP
logger.info('File successfully uploaded to '+ FTPADDR)
except, e:
logger.error('Failed to upload to ftp: '+ str(e))
This doesn't seem to work, I get syntax error, what is the proper way of doing this for logging all kind of exceptions to a file
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(15)
您必须定义要捕获哪种类型的异常。因此,对于一般异常,应将
except Exception 写为 e: 而不是
except, e: 。
另一种可能性是这样编写整个 try/ except 代码:
在旧版本的 Python 2.x 中,使用
except Exception, e 而不是
except Exception as e :
You have to define which type of exception you want to catch. So write
except Exception as e:
instead ofexcept, e:
for a general exception.Other possibility is to write your whole try/except code this way:
In older versions of Python 2.x, use
except Exception, e
instead ofexcept Exception as e
:python 3 不再支持该语法。请改用以下语法。
The syntax is no longer supported in python 3. Use the following instead.
如果您需要错误类、错误消息和堆栈跟踪,请使用
sys.exc_info()
。具有某种格式的最小工作代码:
给出以下输出:
函数 sys.exc_info() 为您提供有关最近异常的详细信息。它返回一个
(类型,值,回溯)
元组。traceback
是traceback 对象的一个实例。您可以使用提供的方法格式化跟踪。更多信息可以在 traceback 文档 中找到。If you want the error class, error message, and stack trace, use
sys.exc_info()
.Minimal working code with some formatting:
Which gives the following output:
The function sys.exc_info() gives you details about the most recent exception. It returns a tuple of
(type, value, traceback)
.traceback
is an instance of traceback object. You can format the trace with the methods provided. More can be found in the traceback documentation .在某些情况下,您可以使用e.message或e.messages..但它并非在所有情况下都有效。无论如何,更安全的是使用 str(e)
There are some cases where you can use the e.message or e.messages.. But it does not work in all cases. Anyway the more safe is to use the str(e)
将其更新为更简单的记录器(适用于 python 2 和 3)。您不需要回溯模块。
现在这是旧方法(尽管仍然有效):
exc_value 是错误消息。
Updating this to something simpler for logger (works for both python 2 and 3). You do not need traceback module.
This is now the old way (though still works):
exc_value is the error message.
使用
str(e)
或repr(e)
来表示异常,您不会获得实际的堆栈跟踪,因此对于查找异常在哪里没有帮助。阅读其他答案和日志记录包文档后,以下两种方法可以很好地打印实际的堆栈跟踪以便于调试:
使用
logger.debug()
和参数exc_info
使用
logger.exception()
或者我们可以直接使用
logger.exception()
来打印异常。Using
str(e)
orrepr(e)
to represent the exception, you won't get the actual stack trace, so it is not helpful to find where the exception is.After reading other answers and the logging package doc, the following two ways works great to print the actual stack trace for easier debugging:
use
logger.debug()
with parameterexc_info
use
logger.exception()
or we can directly use
logger.exception()
to print the exception.您可以使用 logger.exception("msg") 来记录带有回溯的异常:
You can use
logger.exception("msg")
for logging exception with traceback:python 3.6之后,您可以使用格式化字符串文字。很整洁! (https://docs.python.org/3/whatsnew/3.6。 html#whatsnew36-pep498)
After python 3.6, you can use formatted string literal. It's neat! (https://docs.python.org/3/whatsnew/3.6.html#whatsnew36-pep498)
您可以尝试显式指定 BaseException 类型。但是,这只会捕获 BaseException 的派生类。虽然这包括所有实现提供的异常,但也可能引发任意旧式类。
You can try specifying the BaseException type explicitly. However, this will only catch derivatives of BaseException. While this includes all implementation-provided exceptions, it is also possibly to raise arbitrary old-style classes.
如果您想查看原始错误消息,(文件 & 行号)
这将显示与您未使用
try 相同的错误消息-除了
。If you want to see the original error message, (file & line number)
This will show you the same error message as if you didn't use
try-except
.为了未来的奋斗者,
在 python 3.8.2(可能还有之前的几个版本)中,语法是
for the future strugglers,
in python 3.8.2(and maybe a few versions before that), the syntax is
在 Python 3 中,
str(ex)
为我们提供错误消息。您可以使用repr(ex)
获取全文,包括引发的异常的名称。In Python 3,
str(ex)
gives us the error message. You could userepr(ex)
to get the full text, including the name of the exception raised.还有一种方法可以获取传递给异常类的原始值,而无需更改内容类型。
例如,我在我的框架之一中提出带有错误消息的类型代码。
输出
There is also a way to get the raw values passed to the exception class without having to change the content type.
For e.g I raise type codes with error messages in one of my frameworks.
Output
使用str(ex)打印执行
Use str(ex) to print execption
最简单的方法是通过 Polog 库。导入它:
并使用:
注意代码垂直占用的空间少了多少:只有 2 行。
The easiest way to do this is available through the Polog library. Import it:
And use:
Note how much less space the code has taken up vertically: only 2 lines.