#!/usr/bin/env python
#
# Copyright (C) 2013 DNAnexus, Inc.
#
# This file is part of dx-toolkit (DNAnexus platform client libraries).
#
#   Licensed under the Apache License, Version 2.0 (the "License"); you may not
#   use this file except in compliance with the License. You may obtain a copy
#   of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#   WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#   License for the specific language governing permissions and limitations
#   under the License.

'''
Redirects stdin to a DNAnexus log socket in the execution environment.
'''

import sys, logging, argparse
import dxpy

logging.basicConfig(level=logging.DEBUG, format="%(message)s")

parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("-l", "--level", help="Logging level to use", default='info')
parser.add_argument("-s", "--source", help="Source ID to use", default='DX_APP_STREAM',
                    choices=['DX_APP', 'DX_APP_STREAM'])
args = parser.parse_args()

try:
    log_function = logging.__dict__[args.level]
except:
    log_function = logging.info

try:
    logger = logging.getLogger()
    logger.handlers = []
    logger.addHandler(dxpy.DXLogHandler(source=args.source))
except Exception as e:
    print >> sys.stderr, "dx_log_stream: Error while initializing logging:", str(e)
    sys.exit(1)

while True:
    line = sys.stdin.readline()
    if line == '':
        break
    if len(line) > 8192:
        line = line[:8192] + '... [truncated]'
    # print "Logging line:", line.rstrip("\n"), "to log handler w/level", args.level
    log_function(line.rstrip("\n"))
