1365f5b2f39a485182f87c4ddabebba8660ef9d2
[metaproxy-moved-to-github.git] / src / filter_log.cpp
1 /* This file is part of Metaproxy.
2    Copyright (C) Index Data
3
4 Metaproxy is free software; you can redistribute it and/or modify it under
5 the terms of the GNU General Public License as published by the Free
6 Software Foundation; either version 2, or (at your option) any later
7 version.
8
9 Metaproxy is distributed in the hope that it will be useful, but WITHOUT ANY
10 WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12 for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
17 */
18
19 #include "config.hpp"
20 #include "filter_log.hpp"
21 #include <metaproxy/package.hpp>
22
23 #include <string>
24 #include <sstream>
25 #include <iomanip>
26 #include <boost/thread/mutex.hpp>
27
28 #include "gduutil.hpp"
29 #include <metaproxy/util.hpp>
30 #include <metaproxy/xmlutil.hpp>
31
32 #include <yaz/oid_db.h>
33 #include <yaz/zgdu.h>
34 #include <yaz/wrbuf.h>
35 #include <yaz/log.h>
36 #include <yaz/querytowrbuf.h>
37 #include <yaz/timing.h>
38 #include <stdio.h>
39 #include <time.h>
40
41 namespace mp = metaproxy_1;
42 namespace yf = metaproxy_1::filter;
43
44 namespace metaproxy_1 {
45     namespace filter {
46         class Log::Impl {
47         public:
48             class LFile;
49             typedef boost::shared_ptr<Log::Impl::LFile> LFilePtr;
50         public:
51             //Impl();
52             Impl(const std::string &x = "-");
53            ~Impl();
54             void process(metaproxy_1::Package & package);
55             void configure(const xmlNode * ptr);
56         private:
57             void openfile(const std::string &fname);
58             // needs to be static to be called by C pointer-to-function-syntax
59             static void stream_write(ODR o, void *handle, int type,
60                               const char *buf, int len);
61             // needs to be static to be called by C pointer-to-function-syntax
62             static void option_write(const char *name, void *handle);
63         private:
64             std::string m_msg_config;
65             bool m_1line;
66             bool m_access;
67             bool m_user_access;
68             bool m_req_apdu;
69             bool m_res_apdu;
70             bool m_req_session;
71             bool m_res_session;
72             bool m_init_options;
73             LFilePtr m_file;
74             std::string m_time_format;
75             // Only used during confiqgure stage (no threading),
76             // for performance avoid opening files which other log filter
77             // instances already have opened
78             static std::list<LFilePtr> filter_log_files;
79
80             boost::mutex m_session_mutex;
81             std::map<mp::Session, std::string> m_sessions;
82        };
83
84         class Log::Impl::LFile {
85         public:
86             boost::mutex m_mutex;
87             std::string m_fname;
88             FILE *fhandle;
89             ~LFile();
90             LFile(std::string fname);
91             LFile(std::string fname, FILE *outf);
92             void log(const std::string &date_format,
93                      std::ostringstream &os);
94             void flush();
95         };
96
97     }
98 }
99
100 // define Pimpl wrapper forwarding to Impl
101
102 yf::Log::Log() : m_p(new Impl)
103 {
104 }
105
106 yf::Log::Log(const std::string &x) : m_p(new Impl(x))
107 {
108 }
109
110 yf::Log::~Log()
111 {  // must have a destructor because of boost::scoped_ptr
112 }
113
114 void yf::Log::configure(const xmlNode *xmlnode, bool test_only,
115                         const char *path)
116 {
117     m_p->configure(xmlnode);
118 }
119
120 void yf::Log::process(mp::Package &package) const
121 {
122     m_p->process(package);
123 }
124
125
126 // static initialization
127 std::list<yf::Log::Impl::LFilePtr> yf::Log::Impl::filter_log_files;
128
129
130 yf::Log::Impl::Impl(const std::string &x)
131     : m_msg_config(x),
132       m_1line(false),
133       m_access(true),
134       m_user_access(false),
135       m_req_apdu(false),
136       m_res_apdu(false),
137       m_req_session(false),
138       m_res_session(false),
139       m_init_options(false),
140       m_time_format("%H:%M:%S-%d/%m")
141 {
142     openfile("");
143 }
144
145
146 yf::Log::Impl::~Impl()
147 {
148 }
149
150 static void log_DefaultDiagFormat(WRBUF w, Z_DefaultDiagFormat *e)
151 {
152     if (e->condition)
153         wrbuf_printf(w, ODR_INT_PRINTF " ", *e->condition);
154     else
155         wrbuf_puts(w, "?? ");
156     if (e->which == Z_DefaultDiagFormat_v2Addinfo && e->u.v2Addinfo)
157     {
158         wrbuf_puts(w, "\"");
159         wrbuf_puts(w, e->u.v2Addinfo);
160         wrbuf_puts(w, "\"");
161     }
162     else if (e->which == Z_DefaultDiagFormat_v3Addinfo && e->u.v3Addinfo)
163     {
164         wrbuf_puts(w, "\"");
165         wrbuf_puts(w, e->u.v3Addinfo);
166         wrbuf_puts(w, "\"");
167     }
168     else
169         wrbuf_puts(w, "-");
170 }
171
172 static void log_DiagRecs(WRBUF w, int num_diagRecs, Z_DiagRec **diags)
173 {
174     if (diags[0]->which != Z_DiagRec_defaultFormat)
175         wrbuf_puts(w ,"(diag not in default format?)");
176     else
177     {
178         Z_DefaultDiagFormat *e = diags[0]->u.defaultFormat;
179         log_DefaultDiagFormat(w, e);
180     }
181 }
182
183 static void log_syntax(WRBUF w, const Odr_oid *syntax)
184 {
185     if (syntax)
186     {
187         char oid_name[OID_STR_MAX+1];
188         wrbuf_puts(w, yaz_oid_to_string_buf(syntax, 0, oid_name));
189     }
190     else
191         wrbuf_puts(w, "-");
192 }
193
194 static void log_1line_Z_APDU(Z_APDU *z_req, Z_APDU *z_res, WRBUF w)
195 {
196     switch (z_req->which)
197     {
198     case Z_APDU_initRequest:
199         wrbuf_puts(w, "Init ");
200         if (!z_res)
201             wrbuf_puts(w, "?");
202         else if (z_res->which != Z_APDU_initResponse)
203             wrbuf_printf(w, "? response=%d", z_res->which);
204         else
205         {
206             Z_InitRequest *req = z_req->u.initRequest;
207             Z_InitResponse *res = z_res->u.initResponse;
208             if (res->result && *res->result)
209                 wrbuf_printf(w, "OK -");
210             else
211             {
212                 Z_External *uif = res->userInformationField;
213                 bool got_code = false;
214                 wrbuf_printf(w, "ERROR ");
215                 if (uif && uif->which == Z_External_userInfo1)
216                 {
217                     Z_OtherInformation *ui = uif->u.userInfo1;
218                     if (ui->num_elements >= 1)
219                     {
220                         Z_OtherInformationUnit *unit = ui->list[0];
221                         if (unit->which == Z_OtherInfo_externallyDefinedInfo &&
222                             unit->information.externallyDefinedInfo &&
223                             unit->information.externallyDefinedInfo->which ==
224                             Z_External_diag1)
225                         {
226                             Z_DiagnosticFormat *diag =
227                                 unit->information.externallyDefinedInfo->
228                                 u.diag1;
229                             if (diag->num >= 1)
230                             {
231                                 Z_DiagnosticFormat_s *ds = diag->elements[0];
232                                 if (ds->which ==
233                                     Z_DiagnosticFormat_s_defaultDiagRec)
234                                 {
235                                     log_DefaultDiagFormat(w,
236                                                           ds->u.defaultDiagRec);
237                                     got_code = true;
238                                 }
239                             }
240
241                         }
242                     }
243                 }
244                 if (!got_code)
245                     wrbuf_puts(w, "-");
246             }
247             wrbuf_printf(w, " ID:%s Name:%s Version:%s",
248                          req->implementationId ? req->implementationId :"-",
249                          req->implementationName ?req->implementationName : "-",
250                          req->implementationVersion ?
251                          req->implementationVersion : "-");
252         }
253         break;
254     case Z_APDU_searchRequest:
255         wrbuf_puts(w, "Search ");
256         if (!z_res)
257             wrbuf_puts(w, "?");
258         else if (z_res->which != Z_APDU_searchResponse)
259             wrbuf_printf(w, "? response=%d", z_res->which);
260         else
261         {
262             Z_SearchRequest *req = z_req->u.searchRequest;
263             Z_SearchResponse *res = z_res->u.searchResponse;
264             int i;
265             for (i = 0 ; i < req->num_databaseNames; i++)
266             {
267                 if (i)
268                     wrbuf_printf(w, "+");
269                 wrbuf_puts(w, req->databaseNames[i]);
270             }
271             wrbuf_printf(w, " ");
272             if (!res->records)
273             {
274                 wrbuf_printf(w, "OK " ODR_INT_PRINTF " %s", *res->resultCount,
275                              req->resultSetName);
276             }
277             else if (res->records->which == Z_Records_DBOSD)
278             {
279                 wrbuf_printf(w, "OK " ODR_INT_PRINTF " %s", *res->resultCount,
280                              req->resultSetName);
281             }
282             else if (res->records->which == Z_Records_NSD)
283             {
284                 wrbuf_puts(w, "ERROR ");
285                 log_DefaultDiagFormat(w,
286                                       res->records->u.nonSurrogateDiagnostic);
287             }
288             else if (res->records->which == Z_Records_multipleNSD)
289             {
290                 wrbuf_puts(w, "ERROR ");
291                 log_DiagRecs(
292                     w,
293                     res->records->u.multipleNonSurDiagnostics->num_diagRecs,
294                     res->records->u.multipleNonSurDiagnostics->diagRecs);
295             }
296             wrbuf_puts(w, " ");
297             log_syntax(w, req->preferredRecordSyntax);
298             wrbuf_printf(w, " 1+" ODR_INT_PRINTF " ",
299                          res->numberOfRecordsReturned
300                          ? *res->numberOfRecordsReturned : 0);
301             yaz_query_to_wrbuf(w, req->query);
302         }
303         break;
304     case Z_APDU_presentRequest:
305         wrbuf_puts(w, "Present ");
306         if (!z_res)
307             wrbuf_puts(w, "?");
308         else if (z_res->which != Z_APDU_presentResponse)
309             wrbuf_printf(w, "? response=%d", z_res->which);
310         else
311         {
312             Z_PresentRequest *req = z_req->u.presentRequest;
313             Z_PresentResponse *res = z_res->u.presentResponse;
314
315             if (!res->records)
316             {
317                 wrbuf_printf(w, "OK");
318             }
319             else if (res->records->which == Z_Records_DBOSD)
320             {
321                 wrbuf_printf(w, "OK");
322             }
323             else if (res->records->which == Z_Records_NSD)
324             {
325                 wrbuf_puts(w, "ERROR ");
326                 log_DefaultDiagFormat(w,
327                                       res->records->u.nonSurrogateDiagnostic);
328             }
329             else if (res->records->which == Z_Records_multipleNSD)
330             {
331                 wrbuf_puts(w, "ERROR ");
332                 log_DiagRecs(
333                     w,
334                     res->records->u.multipleNonSurDiagnostics->num_diagRecs,
335                     res->records->u.multipleNonSurDiagnostics->diagRecs);
336             }
337             wrbuf_puts(w, " ");
338             assert(req->preferredRecordSyntax);
339             log_syntax(w, req->preferredRecordSyntax);
340
341             wrbuf_printf(w, " %s " ODR_INT_PRINTF "+" ODR_INT_PRINTF " ",
342                 req->resultSetId, *req->resultSetStartPoint,
343                          *req->numberOfRecordsRequested);
344         }
345         break;
346     case Z_APDU_deleteResultSetRequest:
347         wrbuf_puts(w, "deleteResultSet ");
348         break;
349     case Z_APDU_accessControlRequest:
350         wrbuf_puts(w, "accessControl ");
351         break;
352     case Z_APDU_resourceControlRequest:
353         wrbuf_puts(w, "resourceControl ");
354         break;
355     case Z_APDU_triggerResourceControlRequest:
356         wrbuf_puts(w, "triggerResourceControlRequest");
357         break;
358     case Z_APDU_resourceReportRequest:
359         wrbuf_puts(w, "resourceReport ");
360         break;
361     case Z_APDU_scanRequest:
362         wrbuf_puts(w, "Scan ");
363         if (!z_res)
364             wrbuf_puts(w, "?");
365         else if (z_res->which != Z_APDU_scanResponse)
366             wrbuf_printf(w, "? response=%d", z_res->which);
367         else
368         {
369             Z_ScanRequest *req = z_req->u.scanRequest;
370             Z_ScanResponse *res = z_res->u.scanResponse;
371             int i;
372             for (i = 0 ; i < req->num_databaseNames; i++)
373             {
374                 if (i)
375                     wrbuf_printf(w, "+");
376                 wrbuf_puts(w, req->databaseNames[i]);
377             }
378             wrbuf_puts(w, " ");
379             if (!res->scanStatus || *res->scanStatus == 0)
380                 wrbuf_puts(w, "OK");
381             else if (*res->scanStatus == 6)
382                 wrbuf_puts(w, "ERROR");
383             else
384                 wrbuf_printf(w, "PARTIAL" ODR_INT_PRINTF, *res->scanStatus);
385
386             wrbuf_printf(w, " " ODR_INT_PRINTF " " ODR_INT_PRINTF "+"
387                          ODR_INT_PRINTF "+" ODR_INT_PRINTF " ",
388                          res->numberOfEntriesReturned ?
389                          *res->numberOfEntriesReturned : 0,
390                          req->preferredPositionInResponse ?
391                           *req->preferredPositionInResponse : 1,
392                          *req->numberOfTermsRequested,
393                          res->stepSize ? *res->stepSize : 1);
394
395             yaz_scan_to_wrbuf(w, req->termListAndStartPoint,
396                               req->attributeSet);
397         }
398         break;
399     case Z_APDU_sortRequest:
400         wrbuf_puts(w, "sort ");
401         if (!z_res)
402             wrbuf_puts(w, "?");
403         else if (z_res->which != Z_APDU_sortResponse)
404             wrbuf_printf(w, "? response=%d", z_res->which);
405         else
406         {
407             Z_SortResponse *res = z_res->u.sortResponse;
408             Z_SortRequest *req = z_res->u.sortRequest;
409             int i;
410
411             if (*res->sortStatus == Z_SortResponse_success)
412                 wrbuf_puts(w, "OK");
413             else if (*res->sortStatus == Z_SortResponse_partial_1)
414                 wrbuf_puts(w, "PARTIAL");
415             else if (*res->sortStatus == Z_SortResponse_failure)
416                 wrbuf_puts(w, "ERROR");
417
418             wrbuf_puts(w, " ");
419             if (res->diagnostics && res->num_diagnostics >= 1)
420                 log_DiagRecs(w, res->num_diagnostics,res->diagnostics);
421             else
422                 wrbuf_puts(w, "-");
423
424             wrbuf_puts(w, " (");
425             for (i = 0; i < req->num_inputResultSetNames; i++)
426             {
427                 if (i)
428                     wrbuf_puts(w, "+");
429                 wrbuf_puts(w, req->inputResultSetNames[i]);
430             }
431             wrbuf_printf(w, ")->%s ",req->sortedResultSetName);
432
433         }
434         break;
435     case Z_APDU_segmentRequest:
436         wrbuf_puts(w, "segmentRequest");
437         break;
438     case Z_APDU_extendedServicesRequest:
439         wrbuf_puts(w, "extendedServices ");
440         if (!z_res)
441             wrbuf_puts(w, "?");
442         else if (z_res->which != Z_APDU_extendedServicesResponse)
443             wrbuf_printf(w, "? response=%d", z_res->which);
444         else
445         {
446             Z_ExtendedServicesResponse *res =
447                 z_res->u.extendedServicesResponse;
448             switch (*res->operationStatus)
449             {
450             case Z_ExtendedServicesResponse_done:
451                 wrbuf_puts(w, "DONE"); break;
452             case Z_ExtendedServicesResponse_accepted:
453                 wrbuf_puts(w, "ACCEPTED"); break;
454             case Z_ExtendedServicesResponse_failure:
455                 wrbuf_puts(w, "ERROR"); break;
456             default:
457                 wrbuf_printf(w, ODR_INT_PRINTF, *res->operationStatus);
458             }
459             wrbuf_puts(w, " ");
460             if (res->diagnostics && res->num_diagnostics >= 1)
461                 log_DiagRecs(w, res->num_diagnostics,res->diagnostics);
462             else
463                 wrbuf_puts(w, "-");
464         }
465         break;
466     case Z_APDU_close:
467         wrbuf_puts(w, "close");
468         break;
469     case Z_APDU_duplicateDetectionRequest:
470         wrbuf_puts(w, "duplicateDetention ");
471         if (!z_res)
472             wrbuf_puts(w, "?");
473         else if (z_res->which != Z_APDU_duplicateDetectionResponse)
474             wrbuf_printf(w, "? response=%d", z_res->which);
475         else
476         {
477             Z_DuplicateDetectionResponse *res =
478                 z_res->u.duplicateDetectionResponse;
479             if (*res->status)
480                 wrbuf_puts(w, "OK");
481             else
482                 wrbuf_puts(w, "ERROR");
483
484             wrbuf_puts(w, " ");
485             if (res->diagnostics && res->num_diagnostics >= 1)
486                 log_DiagRecs(w, res->num_diagnostics, res->diagnostics);
487             else
488                 wrbuf_puts(w, "-");
489         }
490         break;
491     default:
492         wrbuf_printf(w, "REQ=%d RES=%d", z_req->which, z_res->which);
493     }
494 }
495
496
497 static void log_1line_Z_HTTP(Z_HTTP_Request *req, Z_HTTP_Response *res, WRBUF w)
498 {
499     wrbuf_printf(w, "%s %s HTTP/%s", req->method, req->path, req->version);
500     if (res)
501         wrbuf_printf(w, " %d %d", res->code, res->content_len);
502     else
503         wrbuf_printf(w, " ?");
504 }
505
506 static void log_1line_Z_GDU(Z_GDU *gdu_req, Z_GDU *gdu_res, WRBUF w)
507 {
508     if (gdu_req && gdu_req->which == Z_GDU_Z3950)
509     {
510         log_1line_Z_APDU(gdu_req->u.z3950,
511                          (gdu_res && gdu_res->which == Z_GDU_Z3950) ?
512                          gdu_res->u.z3950 : 0, w);
513     }
514     else if (gdu_req && gdu_req->which == Z_GDU_HTTP_Request)
515     {
516         log_1line_Z_HTTP(gdu_req->u.HTTP_Request,
517                          (gdu_res && gdu_res->which == Z_GDU_HTTP_Response) ?
518                          gdu_res->u.HTTP_Response : 0, w);
519     }
520 }
521
522 void yf::Log::Impl::configure(const xmlNode *ptr)
523 {
524     for (ptr = ptr->children; ptr; ptr = ptr->next)
525     {
526         if (ptr->type != XML_ELEMENT_NODE)
527             continue;
528         if (!strcmp((const char *) ptr->name, "message"))
529             m_msg_config = mp::xml::get_text(ptr);
530         else if (!strcmp((const char *) ptr->name, "filename"))
531         {
532             std::string fname = mp::xml::get_text(ptr);
533             openfile(fname);
534         }
535         else if (!strcmp((const char *) ptr->name, "time-format"))
536         {
537             m_time_format = mp::xml::get_text(ptr);
538         }
539         else if (!strcmp((const char *) ptr->name, "category"))
540         {
541             const struct _xmlAttr *attr;
542             for (attr = ptr->properties; attr; attr = attr->next)
543             {
544                 if (!strcmp((const char *) attr->name,  "line"))
545                     m_1line = mp::xml::get_bool(attr->children, true);
546                 else if (!strcmp((const char *) attr->name,  "access"))
547                     m_access = mp::xml::get_bool(attr->children, true);
548                 else if (!strcmp((const char *) attr->name, "user-access"))
549                     m_user_access = mp::xml::get_bool(attr->children, true);
550                 else if (!strcmp((const char *) attr->name, "request-apdu"))
551                     m_req_apdu = mp::xml::get_bool(attr->children, true);
552                 else if (!strcmp((const char *) attr->name, "response-apdu"))
553                     m_res_apdu = mp::xml::get_bool(attr->children, true);
554                 else if (!strcmp((const char *) attr->name, "apdu"))
555                 {
556                     m_req_apdu = mp::xml::get_bool(attr->children, true);
557                     m_res_apdu = m_req_apdu;
558                 }
559                 else if (!strcmp((const char *) attr->name,
560                                  "request-session"))
561                     m_req_session =
562                         mp::xml::get_bool(attr->children, true);
563                 else if (!strcmp((const char *) attr->name,
564                                  "response-session"))
565                     m_res_session =
566                         mp::xml::get_bool(attr->children, true);
567                 else if (!strcmp((const char *) attr->name,
568                                  "session"))
569                 {
570                     m_req_session =
571                         mp::xml::get_bool(attr->children, true);
572                     m_res_session = m_req_session;
573                 }
574                 else if (!strcmp((const char *) attr->name,
575                                  "init-options"))
576                     m_init_options =
577                         mp::xml::get_bool(attr->children, true);
578                 else if (!strcmp((const char *) attr->name,
579                                  "init-options"))
580                     m_init_options =
581                         mp::xml::get_bool(attr->children, true);
582                 else
583                     throw mp::filter::FilterException(
584                         "Bad attribute " + std::string((const char *)
585                                                        attr->name));
586             }
587         }
588         else
589         {
590             throw mp::filter::FilterException("Bad element "
591                                                + std::string((const char *)
592                                                              ptr->name));
593         }
594     }
595 }
596
597 void yf::Log::Impl::process(mp::Package &package)
598 {
599     Z_GDU *gdu_req = package.request().get();
600     std::string user("-");
601
602     yaz_timing_t timer = yaz_timing_create();
603
604     // scope for session lock
605     {
606         boost::mutex::scoped_lock scoped_lock(m_session_mutex);
607
608         if (gdu_req && gdu_req->which == Z_GDU_Z3950)
609         {
610             Z_APDU *apdu_req = gdu_req->u.z3950;
611             if (apdu_req->which == Z_APDU_initRequest)
612             {
613                 Z_InitRequest *req = apdu_req->u.initRequest;
614                 Z_IdAuthentication *a = req->idAuthentication;
615                 if (a)
616                 {
617                     if (a->which == Z_IdAuthentication_idPass
618                         && a->u.idPass->userId)
619                         user = a->u.idPass->userId;
620                     else if (a->which == Z_IdAuthentication_open)
621                         user = a->u.open;
622
623                     m_sessions[package.session()] = user;
624                 }
625             }
626         }
627         std::map<mp::Session,std::string>::iterator it =
628             m_sessions.find(package.session());
629         if (it != m_sessions.end())
630             user = it->second;
631
632         if (package.session().is_closed())
633             m_sessions.erase(package.session());
634     }
635     // scope for locking Ostream
636     {
637         boost::mutex::scoped_lock scoped_lock(m_file->m_mutex);
638
639         if (m_access)
640         {
641             if (gdu_req)
642             {
643                 std::ostringstream os;
644                 os  << m_msg_config << " "
645                     << package << " "
646                     << "0.000000" << " "
647                     << *gdu_req;
648                 m_file->log(m_time_format, os);
649             }
650         }
651
652         if (m_user_access)
653         {
654             if (gdu_req)
655             {
656                 std::ostringstream os;
657                 os  << m_msg_config << " " << user << " "
658                     << package << " "
659                     << "0.000000" << " "
660                     << *gdu_req;
661                 m_file->log(m_time_format, os);
662             }
663         }
664
665         if (m_req_session)
666         {
667             std::ostringstream os;
668             os << m_msg_config;
669             os << " request id=" << package.session().id();
670             os << " close="
671                << (package.session().is_closed() ? "yes" : "no");
672             m_file->log(m_time_format, os);
673         }
674
675         if (m_init_options)
676         {
677             if (gdu_req && gdu_req->which == Z_GDU_Z3950 &&
678                 gdu_req->u.z3950->which == Z_APDU_initRequest)
679             {
680                 std::ostringstream os;
681                 os << m_msg_config << " init options:";
682                 yaz_init_opt_decode(gdu_req->u.z3950->u.initRequest->options,
683                                     option_write, &os);
684                 m_file->log(m_time_format, os);
685             }
686         }
687
688         if (m_req_apdu)
689         {
690             if (gdu_req)
691             {
692                 mp::odr odr(ODR_PRINT);
693                 odr_set_stream(odr, m_file->fhandle, stream_write, 0);
694                 z_GDU(odr, &gdu_req, 0, 0);
695             }
696         }
697     }
698
699     // unlocked during move
700     package.move();
701
702     Z_GDU *gdu_res = package.response().get();
703
704     gdu_req = package.request().get();
705
706     yaz_timing_stop(timer);
707     double duration = yaz_timing_get_real(timer);
708
709     // scope for locking Ostream
710     {
711         boost::mutex::scoped_lock scoped_lock(m_file->m_mutex);
712
713         if (m_1line)
714         {
715             mp::wrbuf w;
716
717             log_1line_Z_GDU(gdu_req, gdu_res, w);
718             if (w.len() > 0)
719             {
720                 const char *message = wrbuf_cstr(w);
721                 std::ostringstream os;
722                 os  << m_msg_config << " "
723                     << package << " "
724                     << std::fixed << std::setprecision (6) << duration
725                     << " "
726                     << message;
727                 m_file->log(m_time_format, os);
728             }
729         }
730
731         if (m_access)
732         {
733             if (gdu_res)
734             {
735                 std::ostringstream os;
736                 os  << m_msg_config << " "
737                     << package << " "
738                     << std::fixed << std::setprecision (6) << duration
739                     << " "
740                     << *gdu_res;
741                 m_file->log(m_time_format, os);
742             }
743         }
744         if (m_user_access)
745         {
746             if (gdu_res)
747             {
748                 std::ostringstream os;
749                 os  << m_msg_config << " " << user << " "
750                     << package << " "
751                     << std::fixed << std::setprecision (6) << duration << " "
752                     << *gdu_res;
753                 m_file->log(m_time_format, os);
754             }
755         }
756
757         if (m_res_session)
758         {
759             std::ostringstream os;
760             os << m_msg_config;
761             os << " response id=" << package.session().id();
762             os << " close="
763                << (package.session().is_closed() ? "yes " : "no ")
764                << "duration="
765                << std::fixed << std::setprecision (6) << duration;
766             m_file->log(m_time_format, os);
767         }
768
769         if (m_init_options)
770         {
771             if (gdu_res && gdu_res->which == Z_GDU_Z3950 &&
772                 gdu_res->u.z3950->which == Z_APDU_initResponse)
773             {
774                 std::ostringstream os;
775                 os << m_msg_config;
776                 os << " init options:";
777                 yaz_init_opt_decode(gdu_res->u.z3950->u.initResponse->options,
778                                     option_write, &os);
779                 m_file->log(m_time_format, os);
780             }
781         }
782
783         if (m_res_apdu)
784         {
785             if (gdu_res)
786             {
787                 mp::odr odr(ODR_PRINT);
788                 odr_set_stream(odr, m_file->fhandle, stream_write, 0);
789                 z_GDU(odr, &gdu_res, 0, 0);
790             }
791         }
792     }
793     m_file->flush();
794     yaz_timing_destroy(&timer);
795 }
796
797
798 void yf::Log::Impl::openfile(const std::string &fname)
799 {
800     std::list<LFilePtr>::const_iterator it
801         = filter_log_files.begin();
802     for (; it != filter_log_files.end(); it++)
803     {
804         if ((*it)->m_fname == fname)
805         {
806             m_file = *it;
807             return;
808         }
809     }
810     LFilePtr newfile(new LFile(fname));
811     filter_log_files.push_back(newfile);
812     m_file = newfile;
813 }
814
815
816 void yf::Log::Impl::stream_write(ODR o, void *handle, int type, const char *buf, int len)
817 {
818     FILE *f = (FILE*) handle;
819     fwrite(buf, len, 1, f ? f : yaz_log_file());
820 }
821
822 void yf::Log::Impl::option_write(const char *name, void *handle)
823 {
824     std::ostringstream *os = (std::ostringstream *) handle;
825     *os << " " << name;
826 }
827
828
829 yf::Log::Impl::LFile::LFile(std::string fname) :
830     m_fname(fname)
831
832 {
833     if (fname.c_str())
834         fhandle = fopen(fname.c_str(), "a");
835     else
836         fhandle = 0;
837 }
838
839 yf::Log::Impl::LFile::~LFile()
840 {
841 }
842
843 void yf::Log::Impl::LFile::log(const std::string &date_format,
844                                std::ostringstream &os)
845 {
846     if (fhandle)
847     {
848         char datestr[80];
849         time_t ti = time(0);
850 #if HAVE_LOCALTIME_R
851         struct tm tm0, *tm = &tm0;
852         localtime_r(&ti, tm);
853 #else
854         struct tm *tm = localtime(&ti);
855 #endif
856         if (strftime(datestr, sizeof(datestr)-1, date_format.c_str(), tm))
857         {
858             fputs(datestr, fhandle);
859             fputs(" ", fhandle);
860         }
861         fputs(os.str().c_str(), fhandle);
862         fputc('\n', fhandle);
863     }
864     else
865         yaz_log(YLOG_LOG, "%s", os.str().c_str());
866 }
867
868 void yf::Log::Impl::LFile::flush()
869 {
870     if (fhandle)
871         fflush(fhandle);
872 }
873
874 static mp::filter::Base* filter_creator()
875 {
876     return new mp::filter::Log;
877 }
878
879 extern "C" {
880     struct metaproxy_1_filter_struct metaproxy_1_filter_log = {
881         0,
882         "log",
883         filter_creator
884     };
885 }
886
887 /*
888  * Local variables:
889  * c-basic-offset: 4
890  * c-file-style: "Stroustrup"
891  * indent-tabs-mode: nil
892  * End:
893  * vim: shiftwidth=4 tabstop=8 expandtab
894  */
895