cmcf = ngx_http_conf_get_module_main_conf(cf, ngx_http_core_module);
h = ngx_array_push(&cmcf->phases[NGX_HTTP_LOG_PHASE].handlers);
if (h == NULL) {
return NGX_ERROR;
}
*h = ngx_http_keepalive_log_handler;
return NGX_OK;
}
static ngx_int_t
ngx_http_keepalive_log_handler(ngx_http_request_t *r)
{
ngx_fd_t fd;
u_char *p;
u_char msg[KEEPALIVE_LOG_MAX_LOG_LEN];
ngx_http_keepalive_log_main_conf_t *kmcf;
ngx_http_keepalive_log_loc_conf_t *klcf = ngx_http_get_module_loc_conf(r, ngx_http_keepalive_log_module);
if(!klcf->on || !klcf->log) {
return NGX_OK;
}
fd= klcf->log->file->fd;
if (r == r->main) {
u_char portstr[] = "65535";
ngx_str_t serv;
ngx_str_t hostname;
ngx_str_t ip;
serv.data = portstr;
ngx_http_keepalive_log_get_req_info(r, &serv, &hostname, &ip);
#ifdef KEEPALIVE_LOG_DEBUG
kmcf = ngx_http_get_module_main_conf(r, ngx_http_keepalive_log_module);
ngx_log_error(KEEPALIVE_LOG_DEBUG_LEVEL, kmcf->default_log, 0,
"%V %V %V", &ip, &serv, &hostname);
#endif
if (!r->upstream) {
return NGX_OK;
}
ngx_uint_t cached = r->upstream->peer.cached ? 1 : 0;
p = ngx_snprintf(msg, KEEPALIVE_LOG_MAX_LOG_LEN, "%V %V %V %ui\n", ip, serv, hostname, cached);
(void) ngx_write_fd(fd, msg, p - msg);
}
return NGX_OK;
}
static void
ngx_http_keepalive_log_get_req_info(ngx_http_request_t *r, ngx_str_t *serv, ngx_str_t *hostname, ngx_str_t *ip)
{
ngx_http_core_srv_conf_t *cscf = ngx_http_get_module_srv_conf(r, ngx_http_core_module);
if(cscf->server_name.len > 0) {
*serv = cscf->server_name;
} else {
ngx_uint_t port;
port = ntohs(((struct sockaddr_in*)(r->connection->local_sockaddr))->sin_port);
if(port > 0 && port < 65536) {
//用端口来代表server
serv->len = ngx_sprintf(serv->data, "%ui", port) - serv->data;
} else {
ngx_str_set(serv, "-");
}
}
if(r->headers_in.host) {
*hostname = r->headers_in.host->value;
} else {
ngx_str_set(hostname, "-");
}
*ip = r->connection->addr_text;
}
static ngx_log_t
*ngx_log_create(ngx_cycle_t *cycle, ngx_str_t *name)
{
ngx_log_t *log = ngx_pcalloc(cycle->pool, sizeof(ngx_log_t));
if(log == NULL) {
return NULL;
}
log->file = ngx_conf_open_file(cycle, name);
if(log->file == NULL) {
return NULL;
}
return log;
}
static char*
ngx_http_keepalive_log_set_log(ngx_conf_t *cf, ngx_command_t *cmd, void *conf)
{
ngx_http_keepalive_log_loc_conf_t *klcf = conf;
ngx_str_t *value = NULL;
if(klcf->log != NGX_CONF_UNSET_PTR) {
return "is duplicated";
}
value = cf->args->elts;
klcf->log = ngx_log_create(cf->cycle, &value[1]);
if(klcf->log == NULL) {
return NGX_CONF_ERROR;
}
return NGX_CONF_OK;
}
Linux下HAProxy+Keepalived双机高可用方案
Haproxy+Keepalived搭建Weblogic高可用负载均衡集群
CentOS 6.3下Haproxy+Keepalived+Apache配置笔记