Error Logging in HTTP API

INFO: Error Logging in HTTP API

Article ID:820729
Last Review:October 9, 2003
Revision:1.0

SUMMARY

This article describes the error logging capabilities of Hypertext Transfer Protocol (HTTP) APIs.

Some errors that occur in an HTTP-based application are automatically handled by the HTTP API instead of being passed back to an application for handling. This behavior occurs because the frequency of such errors might otherwise flood an event log or an application handler.

The following topics describe the different aspects of HTTP API error logging:
Configure HTTP API Error Logging
Registry settings control the HTTP API logs errors, the maximum permitted size of log files, and the location of the log files.
Format of the HTTP API Error Logs
The HTTP API creates log files that comply with the World Wide Web Consortium (W3C) log file conventions. You can use standard tools to parse these log files. However, unlike W3C log files, HTTP API log files do not contain the columns names.
Types of Errors That the HTTP API Logs
The HTTP API logs a variety of common errors.

MORE INFORMATION

Configure HTTP API Error Logging

Three registry values under an HTTP \Parameters key control the HTTP API error logging. These keys are located at the following registry key:
HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\HTTP\Parameters
Note The location and the form of the configuration values may change in later versions of the Microsoft Windows operating system.

You must have Administrator/Local System credentials to change the registry values, and to view or modify the log files and the folder that contains them.

Configuration information in the registry values is read when the HTTP API driver starts. Therefore, if you change the settings, you must stop, and then restart the driver to read the new values. To do this, type the following console commands:
net stop http
net start http
The following naming convention is used to name the log files:
httperr + sequence number + .log
Example: httperr4.log
Log files are cycled when they reach the maximum size that the ErrorLogFileTruncateSize registry value specifies. This value cannot be less than one megabyte (MB).

If the configuration of error logging is not valid, or if any type of failure occurs while the HTTP API is writing to the log files, the HTTP API uses event logging to notify administrators that error logging is not occurring.

The following table describes the registry configuration values:

Registry ValueDescription
EnableErrorLoggingA DWORD that you can set to TRUE to enable error logging or to FALSE to disable it. The default value is TRUE.
ErrorLogFileTruncateSizeA DWORD that specifies the maximum size of an error log file, in bytes. The default value is one MB (0x100000).

Note The specified value cannot be smaller than the default value.
ErrorLoggingDirA String that specifies the folder where the HTTP API puts its logging files.

The HTTP API creates a subfolder HTTPERR in the specified folder, and then stores the log files in the subfolder. This subfolder and the log files receive the same permission settings. The Administrator and Local System Accounts have full access. Other users do not have access.

The following is the default folder when the folder is not specified in the registry:
%SystemRoot%\System32\LogFiles

Note The ErrorLoggingDir string value must be a fully qualified path. However, it can contain %SystemRoot%.

back to the top

Format of the HTTP API Error Logs

Generally, HTTP API error log files have the same format as W3C error logs, except that HTTP API error log files do not contain column headings. Each line of an HTTP API error log records one error. The fields appear in a specific order. A single space character (0x0020) separates each field from the previous field. In each field, plus signs (0x002B) replace space characters, tabs, and nonprintable control characters.

The following table identifies the fields and the order of the fields in an error log record:

FieldDescription
DateThe Date field follows the W3C format. This field is based on Coordinated Universal Time (UTC). The Date field is always ten characters in the form of YYYY-MM-DD. For example, May 1, 2003 is expressed as 2003-05-01.
TimeThe Time field follows the W3C format. This field is based on UTC. The time field is always eight characters in the form of MM:HH:SS. For example, 5:30 PM (UTC) is expressed as 17:30:00.
Client IP AddressThe IP address of the affected client. The value in this field can be either an IPv4 address or an IPv6 address. If the client IP address is an IPv6 address, the ScopeId field is also included in the address.
Client PortThe port number for the affected client.
Server IP AddressThe IP address of the affected server. The value in this field can be either an IPv4 address or an IPv6 address. If the server IP address is an IPv6 address, the ScopeId field is also included in the address.
Server PortThe port number of the affected server.
Protocol VersionThe version of the protocol that is being used.

If the connection has not been parsed sufficiently to determine the protocol version, a hyphen (0x002D) is used as a placeholder for the empty field.

If either the major version number or the minor version number that is parsed is greater than or equal to 10, the version is logged as HTTP/?.?.
VerbThe verb state that the last request that is parsed passes. Unknown verbs are included, but any verb that is more than 255 bytes is truncated to this length. If a verb is not available, a hyphen (0x002D) is used as a placeholder for the empty field.
CookedURL + QueryThe URL and any query that is associated with it are logged as one field that is separated by a question mark (0x3F). This field is truncated at its length limit of 4096 bytes.

If this URL has been parsed ("cooked"), it is logged with local code page conversion, and is treated as a Unicode field.

If this URL has not been parsed ("cooked") at the time of logging, it is copied exactly, without any Unicode conversion.

If the HTTP API cannot parse this URL, a hyphen (0x002D) is used as a placeholder for the empty field.
Protocol StatusThe protocol status cannot be greater than 999.

If the protocol status of the response to a request is available, it is logged in this field.

If the protocol status is not available, a hyphen (0x002D) is used as a placeholder for the empty field.
SiteIdNot used in this version of the HTTP API. A placeholder hyphen (0x002D) always appears in this field.
Reason PhraseThis field contains a string that identifies the type of error that is being logged. This field is never left empty.
Queue NameThis the request queue name.

The following sample lines are from an HTTP API error log:
2002-07-05 18:45:09 172.31.77.6 2094 172.31.77.6 80 HTTP/1.1 GET /qos/1kbfile.txt 503 – ConnLimit 2002-07-05 19:51:59 127.0.0.1 2780 127.0.0.1 80 HTTP/1.1 GET /ThisIsMyUrl.htm 400 – Hostname 2002-07-05 19:53:00 127.0.0.1 2894 127.0.0.1 80 HTTP/2.0 GET / 505 - Version_N/S 2002-07-05 20:06:01 172.31.77.6 64388 127.0.0.1 80 - - - - - Timer_MinBytesPerSecond
back to the top

Types of Errors That the HTTP API Logs

The HTTP API logs error responses to clients, connection time-outs, orphaned requests, and dropped connections that are handled incorrectly.

The following list identifies the types of errors that the HTTP API logs:
Responses to clients The HTTP API sends an error response to a client, for example, a 400 error that is caused by a parse error in the last received request. After the HTTP API sends the error response, it terminates the connection.
Connection time-outs The HTTP API times out a connection. If a request is pending when the connection times out, the request is used to provide more information about the connection in the error log.
Orphaned requests A user-mode process quits unexpectedly while there are still queued requests that are routed to that process. The HTTP API logs the orphaned requests in the error log.
Specific error types are designated by Reason Phrase strings that always appear as the last field of each error line. The following table identifies the HTTP API Reason Phrases:

Reason Phrase Description

AppOfflineA service unavailable error occurred (an HTTP error 503). The service is not available because application errors caused the application to be taken offline.
AppPoolTimerA service unavailable error occurred (an HTTP error 503). The service is not available because the application pool process is too busy to handle the request.
AppShutdownA service unavailable error occurred (an HTTP error 503). The service is not available because the application shut down automatically in response to administrator policy.
BadRequestA parse error occurred while processing a request.
Connection_Abandoned_By_AppPoolA worker process from the application pool that quit unexpectedly or orphaned a pending request by closing its handle.
Connection_DroppedReserved. Not currently used.
ConnLimitA service unavailable error occurred (an HTTP error 503). The service is not available because the site level connection limit has been reached or exceeded.
DisabledA service unavailable error occurred (an HTTP error 503). The service is not available because an administrator has taken the application offline.
EntityTooLargeAn entity exceeded the maximum size that is permitted.
FieldLengthA field length limit was exceeded.
ForbiddenA forbidden element or sequence was encountered while parsing.
HeaderA parse error occurred in a header.
HostnameA parse error occurred while processing a Hostname.
InternalAn internal server error occurred (an HTTP error 500).
Invalid_CR/LFAn illegal carriage return or line feed occurred.
LengthRequiredA required length value was missing.
N/AA service unavailable error occurred (an HTTP error 503). The service is not available because an internal error (such as a memory allocation failure) occurred.
N/IA not-implemented error occurred (an HTTP error 501), or a service unavailable error occurred (an HTTP error 503) because of an unknown transfer encoding.
NumberA parse error occurred while processing a number.
PreconditionA required precondition was missing.
QueueFullA service unavailable error occurred (an HTTP error 503). The service is not available because the application request queue is full.
RequestLengthA request length limit was exceeded.
Timer_AppPoolThe connection expired because a request waited too long in an application pool queue for a server application to dequeue and process it. This timeout duration is ConnectionTimeout. By default, this value is set to two minutes.
Timer_ConnectionIdleThe connection expired and remains idle. The default ConnectionTimeout duration is two minutes.
Timer_EntityBodyThe connection expired before the request entity body arrived. When it is clear that a request has an entity body, the HTTP API turns on the Timer_EntityBody timer. Initially, the limit of this timer is set to the ConnectionTimeout value (typically 2 minutes). Each time another data indication is received on this request, the HTTP API resets the timer to give the connection two more minutes (or whatever is specified in ConnectionTimeout).
Timer_HeaderWaitThe connection expired because the header parsing for a request took more time than the default limit of two minutes.
Timer_MinBytesPerSecondThe connection expired because the client was not receiving a response at a reasonable speed. The response send rate was slower than the default of 150 bytes/sec.
Timer_ResponseReserved. Not currently used.
URLA parse error occurred while processing a URL.
URL_LengthA URL exceeded the maximum permitted size.
VerbA parse error occurred while processing a verb.
Version_N/SA version-not-supported error occurred (an HTTP error 505).

back to the top

APPLIES TO
Microsoft Windows Server 2003, Datacenter Edition
Microsoft Windows Server 2003, Enterprise Edition
Microsoft Windows Server 2003, Standard Edition
Microsoft Windows Server 2003, Web Edition
Microsoft Windows Small Business Server 2003 Premium Edition
Microsoft Windows Small Business Server 2003 Standard Edition
Keywords:
kberrmsg kbinfo kbhttp kbapi kbhttphandlers KB820729
<think>我们被要求回答关于Python中logging.error函数的使用方法和作用。同时,我们需要参考之前提供的引用内容,并确保在回答中适当引用。此外,用户之前的问题是关于`raise`语句的,但当前问题是关于logging.error的,所以我们需要专注于logging.error。 根据引用内容,我们可以总结以下几点: - logging模块提供了不同级别的日志记录,包括debug、info、warning、error、critical。 - error级别用于记录错误日志,表示无法修复的严重错误,必须立即处理并可能需要停止程序(引用[2])。 - 我们可以使用basicConfig进行配置,包括日志文件名、格式、时间格式和日志级别(引用[2][3])。 - logging.error()的使用方法与其他日志级别类似,可以传递字符串消息,也支持字符串格式化(引用[4])。 因此,回答应包括: 1. logging.error的作用:记录错误级别的日志信息。 2. 使用场景:当发生严重错误,且无法恢复时使用。 3. 使用方法:直接调用logging.error(msg)或使用格式化字符串。 4. 配置:需要先配置日志(如使用basicConfig)才能有效记录,否则可能使用默认设置(输出到控制台,级别为WARNING以上)。 同时,我们需要生成相关问题。 注意:在回答中,如果引用到之前提供的引用内容,需要在引用处添加引用标识,例如[^1]。 </think>### Python `logging.error()`函数详解 `logging.error()`是Python日志系统中关键的**错误记录函数**,专门用于记录程序运行中的严重错误事件。其核心作用是**捕获并持久化错误信息**,同时提供上下文追踪能力(如时间戳、代码位置等),远强于简单的`print()`输出[^1][^2]。 --- #### 一、核心作用与定位 在日志级别体系中(如图),`error`属于高优先级级别: ```mermaid graph LR A[DEBUG] --> B[INFO] --> C[WARNING] --> D[ERROR] --> E[CRITICAL] ``` - **适用场景**:记录**不可恢复的严重错误**(如数据库连接失败、文件损坏等) - **关键特性**: - 触发条件:需人工调用`logging.error()`明确记录 - 默认行为:当日志级别设为`WARNING`及以上时自动输出 - 输出目标:可配置到文件/控制台/网络等[^2] --- #### 二、基础使用方法 ##### 1. 最小化示例 ```python import logging # 配置基础日志(输出到控制台) logging.basicConfig(level=logging.INFO) try: 1 / 0 except ZeroDivisionError: logging.error("发生除零错误") # 记录错误信息 ``` **输出**: ``` ERROR:root:发生除零错误 ``` ##### 2. 结构化错误信息 支持**占位符格式化**,避免字符串拼接[^4]: ```python def process_file(filename): try: with open(filename) as f: ... except FileNotFoundError: logging.error("文件不存在: %s", filename) # 安全格式化 ``` ##### 3. 捕获异常堆栈 通过`exc_info=True`自动附加异常追踪: ```python try: risky_operation() except Exception: logging.error("操作失败", exc_info=True) # 输出完整堆栈 ``` 输出包含: ``` ERROR:操作失败 Traceback (most recent call last): File "demo.py", line 5, in <module> risky_operation() ... ``` --- #### 三、进阶应用技巧 ##### 1. 结合上下文信息 在日志格式中嵌入额外数据(如行号、模块名)[^2][^3]: ```python logging.basicConfig( format='%(asctime)s [%(levelname)s] %(filename)s:%(lineno)d - %(message)s', datefmt='%Y-%m-%d %H:%M:%S' ) logging.error("数据库连接超时") # 输出: 2023-08-20 14:30:05 [ERROR] app.py:42 - 数据库连接超时 ``` ##### 2. 自定义错误处理器 定向发送`error`日志到指定渠道: ```python from logging.handlers import SMTPHandler # 配置邮件报警(仅发送ERROR及以上日志) email_handler = SMTPHandler( mailhost='smtp.example.com', fromaddr='alerts@example.com', toaddrs=['admin@example.com'], subject='应用错误警报' ) email_handler.setLevel(logging.ERROR) logging.getLogger().addHandler(email_handler) ``` ##### 3. 与`try/except`协作 在异常处理中记录原始错误: ```python try: validate_input(data) except ValueError as ve: logging.error("输入验证失败: %s", ve, exc_info=True) raise # 重新抛出 ``` --- #### 四、与`print()`的关键差异 | 特性 | `logging.error()` | `print()` | |-----------------------|--------------------------------|------------------------| | **错误级别标识** | 明确标记`[ERROR]` | 无级别标识 | | **上下文信息** | 支持时间戳、代码位置等 | 仅输出原始字符串 | | **输出目标控制** | 可同时输出到文件/邮件/控制台 | 仅控制台 | | **生产环境适用性** | 支持动态日志级别调整 | 需手动删除或注释 | | **性能影响** | 异步写入避免阻塞主线程 | 同步输出可能阻塞 | > 最佳实践:**生产环境中始终用`logging.error()`替代错误打印**[^1]。 --- #### 五、实战场景示例 ##### 1. Web服务错误监控 ```python from flask import Flask import logging app = Flask(__name__) @app.route('/api/data') def get_data(): try: return fetch_remote_data() except ConnectionError: logging.error("远程API不可访问", exc_info=True) return "服务异常", 500 ``` ##### 2. 批处理作业日志 ```python def batch_process(items): error_count = 0 for item in items: try: process(item) except ProcessingError as pe: logging.error("处理失败: ID=%s 原因=%s", item.id, pe) error_count += 1 logging.info("作业完成 错误率: %.2f%%", (error_count/len(items))*100) ``` --- #### 六、常见错误规避 1. **信息模糊** ```python # 错误做法 logging.error("操作出错") # 正确做法 logging.error("用户%d付款失败: 余额不足 (需¥%.2f)", user_id, amount) ``` 2. **泄露敏感数据** ```python # 危险:记录密码 logging.error("登录失败: username=%s password=%s", user, pwd) # 安全:脱敏处理 logging.error("用户%s登录失败", user) ``` 3. **忽略异常上下文** ```python try: db.commit() except SQLException: # 丢失错误详情 logging.error("数据库提交失败") # 正确:附加异常对象 except SQLException as se: logging.error("数据库错误: %s", se) ``` --- ### 最佳实践总结 1. **明确错误边界**:仅在不可恢复错误时使用`error`级别 2. **结构化日志**:使用格式化占位符`%s`/`%d`代替`f-string`[^4] 3. **保留上下文**:始终传递异常对象或设置`exc_info=True` 4. **分离通道**:将`ERROR`日志定向到报警系统 5. **避免过度使用**:非关键问题用`WARNING`级别 > 关键原则:**日志应满足事后故障诊断需求**,包含足够定位问题的信息[^2]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值