passage sur le Logger Python

This commit is contained in:
Romain Beuque 2014-09-17 02:54:18 +02:00
parent 34e685ff43
commit 4380dac521
8 changed files with 96 additions and 47 deletions

View File

@ -7,6 +7,7 @@ from tg.decorators import expose, validate
from brie.config import ldap_config
from brie.lib.ldap_helper import *
from brie.lib.aurore_helper import *
from brie.lib.log_helper import BrieLogging
from brie.model.ldap import *
from brie.controllers import auth
@ -62,24 +63,24 @@ class GroupController(AuthenticatedBaseController):
def grace_cotisation(self, group_cn):
group = Groupes.get_by_cn(self.user, self.user.residence_dn, group_cn)
print("[LOG "+datetime.now().strftime("%Y-%m-%d %H:%M")+"] start grace du groupe "+ group.dn + " par l'admin "+ self.user.attrs.dn)
BrieLogging.get().info("start grace du groupe "+ group.dn + " par l'admin "+ self.user.attrs.dn)
for user_dn in group.get('uniqueMember').all():
current_year = CotisationComputes.current_year()
cotisations = Cotisation.cotisations_of_member(self.user, user_dn, current_year)
for cotisation in cotisations:
if cotisation.has('x-paymentCashed') and cotisation.get('x-paymentCashed').first() == 'TRUE':
print("[LOG "+datetime.now().strftime("%Y-%m-%d %H:%M")+"] impossible de gracier une cotisation encaissee pour l'utilisateur "+ user_dn + " par l'admin "+ self.user.attrs.dn)
BrieLogging.get().warn("impossible de gracier une cotisation encaissee pour l'utilisateur "+ user_dn + " par l'admin "+ self.user.attrs.dn)
else:
old_montant = cotisation.get("x-amountPaid").first()
cotisation.get("x-amountPaid").replace(cotisation.get("x-amountPaid").first(), 0)
self.user.ldap_bind.save(cotisation)
print("[LOG "+datetime.now().strftime("%Y-%m-%d %H:%M")+"] cotisation graciee (" + old_montant + "EUR) pour l'utilisateur "+ user_dn + " par l'admin "+ self.user.attrs.dn)
BrieLogging.get().info("cotisation graciee (" + old_montant + "EUR) pour l'utilisateur "+ user_dn + " par l'admin "+ self.user.attrs.dn)
#end if
#end for(cotisation)
#end for(users)
print("[LOG "+datetime.now().strftime("%Y-%m-%d %H:%M")+"] fin du grace_bulk_action du groupe "+ group.dn + " par l'admin "+ self.user.attrs.dn)
BrieLogging.get().info("fin du grace_bulk_action du groupe "+ group.dn + " par l'admin "+ self.user.attrs.dn)
redirect("/administration/")
#end def

View File

@ -9,6 +9,7 @@ from brie.config import groups_enum
from brie.lib.ldap_helper import *
from brie.lib.plugins import *
from brie.lib.aurore_helper import *
from brie.lib.log_helper import BrieLogging
from brie.model.ldap import *
from brie.lib.name_translation_helpers import Translations
@ -96,7 +97,7 @@ class MemberAddController(AuthenticatedRestController):
def year_directory_exists(year):
search = self.user.ldap_bind.search(ldap_config.username_base_dn + residence_dn,"(ou="+str(year)+")")
if len(search) == 0:
print "[LOG]Year "+str(year)+" directory does not exist. Creating."
BrieLogging.get().info("Year "+str(year)+" directory does not exist. Creating.")
directory_attrs = {
"objectClass" : ["top","organizationalUnit"],
"ou" : str(year).encode("utf-8")
@ -307,7 +308,7 @@ class MemberDisableController(AuthenticatedRestController):
#end if
#end for
print("[LOG "+datetime.now().strftime("%Y-%m-%d %H:%M") +"] disable member "+member_uid+" by "+self.user.attrs.dn)
BrieLogging.get().info("disable member "+member_uid+" by "+self.user.attrs.dn)
# On redirige sur la page d'édition du membre
redirect("/edit/member/" + residence + "/" + member_uid)
@ -341,7 +342,7 @@ class MemberEnableController(AuthenticatedRestController):
#end if
#end for
print("[LOG "+datetime.now().strftime("%Y-%m-%d %H:%M") +"] enable member "+member_uid+" by "+self.user.attrs.dn)
BrieLogging.get().info("enable member "+member_uid+" by "+self.user.attrs.dn)
# On redirige sur la page d'édition du membre
redirect("/edit/member/" + residence + "/" + member_uid)
@ -393,7 +394,7 @@ class MemberDeleteController(AuthenticatedRestController):
#on supprime le membre
self.user.ldap_bind.delete_entry_subtree(member.dn)
print("[LOG "+datetime.now().strftime("%Y-%m-%d %H:%M") +"] suppression du membre "+member_uid+" by "+self.user.attrs.dn)
BrieLogging.get().info("suppression du membre "+member_uid+" by "+self.user.attrs.dn)
# On redirige sur la page de la residence
redirect("/rooms/index/" + residence)
@ -539,7 +540,7 @@ class MachineAddController(AuthenticatedRestController):
self.user.ldap_bind.add_entry(dns_dn, machine_dns)
# Ajout de l'entrée dans les logs
print("[LOG "+datetime.now().strftime("%Y-%m-%d %H:%M") +"] ajout machine " + mac + " pour l'utilisateur "+ member.dn + " par l'admin "+ self.user.attrs.dn)
BrieLogging.get().info("ajout machine " + mac + " pour l'utilisateur "+ member.dn + " par l'admin "+ self.user.attrs.dn)
plugin_vars = {
"machine_dn" : machine_dn,
@ -595,7 +596,7 @@ class CotisationDeleteController(AuthenticatedRestController):
self.user.ldap_bind.delete_entry_subtree(cotisation.dn)
print("[LOG "+datetime.now().strftime("%Y-%m-%d %H:%M") +"] suppression cotisation (" + cotisation.get('x-amountPaid').first() + "EUR) pour l'utilisateur "+ member.dn + " par l'admin "+ self.user.attrs.dn)
BrieLogging.get().info("suppression cotisation (" + cotisation.get('x-amountPaid').first() + "EUR) pour l'utilisateur "+ member.dn + " par l'admin "+ self.user.attrs.dn)
if go_redirect:
redirect("/edit/member/"+residence+"/"+member_uid)
@ -630,7 +631,7 @@ class CotisationGraceController(AuthenticatedRestController):
cotisation.get("x-amountPaid").replace(cotisation.get("x-amountPaid").first(), 0)
self.user.ldap_bind.save(cotisation)
print("[LOG "+datetime.now().strftime("%Y-%m-%d %H:%M") + "cotisation graciee (" + old_montant + "EUR) pour l'utilisateur "+ member.dn + " par l'admin "+ self.user.attrs.dn)
BrieLogging.get().info("cotisation graciee (" + old_montant + "EUR) pour l'utilisateur "+ member.dn + " par l'admin "+ self.user.attrs.dn)
redirect("/edit/member/"+residence+"/"+member_uid)
@ -751,11 +752,13 @@ class CotisationAddController(AuthenticatedRestController):
if cotisation is not None:
cotisation_dn = "cn=cotisation-" + time + "," + year_dn
BrieLogging.get().info("cotisation ajoutée pour "+ member.dn +"("+cotisation.get("x-amountPaid").first()+"EUR) by "+ self.user.attrs.dn)
self.user.ldap_bind.add_entry(cotisation_dn, cotisation)
#end if
if extra is not None:
extra_dn = "cn=extra-" + time + "," + year_dn
BrieLogging.get().info("extra ajouté pour "+ member.dn +"("+extra.get("x-amountPaid").first()+"EUR) by "+ self.user.attrs.dn)
self.user.ldap_bind.add_entry(extra_dn, extra)
#end if
@ -788,7 +791,7 @@ class MachineDeleteController(AuthenticatedRestController):
# Si la machine existe effectivement, on la supprime
if machine is not None:
# Ajout de l'entrée dans les logs
print("[LOG "+datetime.now().strftime("%Y-%m-%d %H:%M") +"] suppression machine " + Machine.get_dhcps(self.user, machine.dn)[0].get("dhcpHWAddress").values[0] + " pour l'utilisateur "+ member.dn + " par l'admin "+ self.user.attrs.dn)
BrieLogging.get().info("suppression machine " + Machine.get_dhcps(self.user, machine.dn)[0].get("dhcpHWAddress").values[0] + " pour l'utilisateur "+ member.dn + " par l'admin "+ self.user.attrs.dn)
self.user.ldap_bind.delete_entry_subtree(machine.dn)
@ -834,7 +837,7 @@ class MachineDisableController(AuthenticatedRestController):
self.user.ldap_bind.save(machine)
#end if
print("[LOG "+datetime.now().strftime("%Y-%m-%d %H:%M") +"] disable member "+member_uid+" machine "+ machine.dhcpStatements.first().split(" ")[1] +" by "+self.user.attrs.dn)
BrieLogging.get().info("disable member "+member_uid+" machine "+ machine.dhcpStatements.first().split(" ")[1] +" by "+self.user.attrs.dn)
# On redirige sur la page d'édition du membre
redirect("/edit/member/" + residence + "/" + member_uid)
@ -869,7 +872,7 @@ class MachineEnableController(AuthenticatedRestController):
self.user.ldap_bind.save(machine)
#end if
print("[LOG "+datetime.now().strftime("%Y-%m-%d %H:%M") +"] enable member "+member_uid+" machine "+ mac +" by "+self.user.attrs.dn)
BrieLogging.get().info("enable member "+member_uid+" machine "+ mac +" by "+self.user.attrs.dn)
# On redirige sur la page d'édition du membre
redirect("/edit/member/" + residence + "/" + member_uid)
@ -979,6 +982,7 @@ class RoomMoveController(AuthenticatedRestController):
member_in = room.get('x-memberIn').first()
if member_in is not None:
if erase:
BrieLogging.get().info("ecrasement de chambre - passage en sdf pour "+member_in+" chambre "+room_uid+" by"+self.user.attrs.dn)
self.user.ldap_bind.delete_attr(room.dn, { "x-memberIn" : member_in })
else:
raise Exception("chambre de destination non vide")
@ -991,16 +995,16 @@ class RoomMoveController(AuthenticatedRestController):
#end if
self.user.ldap_bind.add_attr(room.dn, memberIn_attribute)
if old_room is not None:
print("[LOG "+datetime.now().strftime("%Y-%m-%d %H:%M") +"] demenagement member "+member_uid+" from "+ old_room.uid.first() +" to "+ room_uid +" by "+self.user.attrs.dn)
BrieLogging.get().info("demenagement member "+member_uid+" from "+ old_room.uid.first() +" to "+ room_uid +" by "+self.user.attrs.dn)
else:
print("[LOG "+datetime.now().strftime("%Y-%m-%d %H:%M") +"] demenagement member "+member_uid+" to "+ room_uid +" by "+self.user.attrs.dn)
BrieLogging.get().info("demenagement member "+member_uid+" to "+ room_uid +" by "+self.user.attrs.dn)
#end if
else:
old_room = Room.get_by_member_dn(self.user, residence_dn, member.dn)
memberIn_attribute = Room.memberIn_attr(str(member.dn))
if old_room is not None:
self.user.ldap_bind.delete_attr(old_room.dn, memberIn_attribute)
print("[LOG "+datetime.now().strftime("%Y-%m-%d %H:%M") +"] retrait de chambre pour le member "+member_uid+" from "+ old_room.uid.first() +" by "+self.user.attrs.dn)
BrieLogging.get().info("retrait de chambre pour le member "+member_uid+" from "+ old_room.uid.first() +" by "+self.user.attrs.dn)
#end if
#end if
@ -1051,13 +1055,13 @@ class RoomChangeMemberController(AuthenticatedRestController):
if room.get("x-memberIn") is not None and room.get("x-memberIn").first() is not None:
memberIn_attribute = Room.memberIn_attr(str(room.get("x-memberIn").first()))
self.user.ldap_bind.delete_attr(room.dn, memberIn_attribute)
print("[LOG "+datetime.now().strftime("%Y-%m-%d %H:%M") +"] retrait de chambre pour le member "+room.get("x-memberIn").first() +" from "+ room_uid +" by "+self.user.attrs.dn)
BrieLogging.get().info("retrait de chambre pour le member "+room.get("x-memberIn").first() +" from "+ room_uid +" by "+self.user.attrs.dn)
#end if
if member is not None:
memberIn_attribute = Room.memberIn_attr(str(member.dn))
self.user.ldap_bind.add_attr(room.dn, memberIn_attribute)
print("[LOG "+datetime.now().strftime("%Y-%m-%d %H:%M") +"] ajout de chambre pour le member "+ member_uid +" to "+ room_uid +" by "+self.user.attrs.dn)
BrieLogging.get().info("ajout de chambre pour le member "+ member_uid +" to "+ room_uid +" by "+self.user.attrs.dn)
#end if
# On redirige sur la page d'édition du membre

View File

@ -7,6 +7,7 @@ from brie.config import ldap_config
from brie.config import groups_enum
from brie.lib.ldap_helper import *
from brie.lib.aurore_helper import *
from brie.lib.log_helper import BrieLogging
from brie.model.ldap import *
from brie.controllers import auth
@ -44,7 +45,7 @@ class RoomsController(AuthenticatedBaseController):
def index(self, residence_name):
status = dict()
areas = dict()
print str(datetime.datetime.now()) + "RoomsIndex0"
BrieLogging.get().debug(str(datetime.datetime.now()) + "RoomsIndex0")
residence_dn = Residences.get_dn_by_name(self.user, residence_name)
if residence_dn is None:
raise Exception("unknown residence")
@ -52,12 +53,12 @@ class RoomsController(AuthenticatedBaseController):
current_year = CotisationComputes.current_year()
cotisations_year = Cotisation.get_all_cotisation_by_year(self.user, residence_dn, current_year)
print str(datetime.datetime.now()) + "RoomsIndex1 - cotis"
BrieLogging.get().debug(str(datetime.datetime.now()) + "RoomsIndex1 - cotis")
stats = CotisationComputes.members_status_from_list_cotisations(self.user, residence_dn, cotisations_year)
print str(datetime.datetime.now()) + "RoomsIndex2 - cotisComput"
BrieLogging.get().debug(str(datetime.datetime.now()) + "RoomsIndex2 - cotisComput")
members = dict()
members_entries = Member.get_all(self.user, residence_dn)
print str(datetime.datetime.now()) + "RoomsIndex3 - members"
BrieLogging.get().debug(str(datetime.datetime.now()) + "RoomsIndex3 - members")
members_entries_dict = dict()
for member in members_entries:
members_entries_dict[member.dn] = member
@ -78,7 +79,7 @@ class RoomsController(AuthenticatedBaseController):
stats['number_of_rooms'] = Room.get_number_of_rooms(self.user, residence_dn)
stats['empty_rooms'] = []
print str(datetime.datetime.now()) + "RoomsIndex4"
BrieLogging.get().debug(str(datetime.datetime.now()) + "RoomsIndex4")
myResidence = self.user.ldap_bind.get_childs(ldap_config.room_base_dn + residence_dn);
for batKey, bat in myResidence.childs.iteritems():

View File

@ -3,6 +3,7 @@ from apscheduler.scheduler import Scheduler
from brie.config import ldap_config
from brie.lib.ldap_helper import *
from brie.lib.aurore_helper import *
from brie.lib.log_helper import BrieLogging
from brie.model.ldap import *
import sys
import datetime
@ -24,7 +25,7 @@ sched = Scheduler()
def disconnect_members_from_residence(admin_user, residence_dn):
members = Member.get_all_non_admin(admin_user, residence_dn)
print (CotisationComputes.current_year())
BrieLogging.get().debug(CotisationComputes.current_year())
date_actuelle = datetime.datetime.now()
for member in members:
@ -38,7 +39,7 @@ def disconnect_members_from_residence(admin_user, residence_dn):
for dhcp_item in dhcps:
if dhcp_item.uid.first() == machine_membre_tag:
print("[LOG "+datetime.datetime.now().strftime("%Y-%m-%d %H:%M")+"] scheduler disable machine " + dhcp_item.get("dhcpHWAddress").values[0] + " pour l'utilisateur "+ member.dn + " -- "+ dhcp_item.dn)
BrieLogging.get().info("scheduler disable machine " + dhcp_item.get("dhcpHWAddress").values[0] + " pour l'utilisateur "+ member.dn + " -- "+ dhcp_item.dn)
dhcp_item.uid.replace(machine_membre_tag, machine_membre_tag + "_disabled")
admin_user.ldap_bind.save(dhcp_item)
#end if
@ -55,17 +56,17 @@ def disconnect_members_from_residence(admin_user, residence_dn):
for machine in machines:
dns = Machine.get_dns_by_id(admin_user, machine.dn)
if dns is None:
print "[LOG] Suppression machine erreur (dns is None): " + machine.dn
BrieLogging.get().info("Suppression machine erreur (dns is None): " + machine.dn)
continue
#end if
ip = IpReservation.get_ip(admin_user, residence_dn, dns.dlzData.first())
print("[LOG "+datetime.datetime.now().strftime("%Y-%m-%d %H:%M")+"] suppression machine " + Machine.get_dhcps(admin_user, machine.dn)[0].get("dhcpHWAddress").values[0] + " pour l'utilisateur "+ member.dn + " par le scheduler")
BrieLogging.get().info("suppression machine " + Machine.get_dhcps(admin_user, machine.dn)[0].get("dhcpHWAddress").values[0] + " pour l'utilisateur "+ member.dn + " par le scheduler")
#sys.stdout.flush()
admin_user.ldap_bind.delete_entry_subtree(machine.dn)
if ip is not None:
taken_attribute = ip.get("x-taken").first()
if taken_attribute is not None:
print ("[LOG "+datetime.datetime.now().strftime("%Y-%m-%d %H:%M")+"] deleting taken_attribute")
BrieLogging.get().debug("deleting taken_attribute for this IP address")
admin_user.ldap_bind.delete_attr(ip.dn, IpReservation.taken_attr(taken_attribute))
#end if
#end if
@ -84,12 +85,12 @@ def disconnect_members_job():
residences = Residences.get_residences(user)
for residence in residences:
print "Disconnect job on : " + residence.uniqueMember.first()
BrieLogging.get().info("Disconnect job on : " + residence.uniqueMember.first())
try:
disconnect_members_from_residence(user, residence.uniqueMember.first())
except Exception as inst:
print "[LOG "+datetime.datetime.now().strftime("%Y-%m-%d %H:%M")+"] Exception sur le scheduler ("+ residence.uniqueMember.first() +")"
print type(inst)
BrieLogging.get().info("Exception sur le scheduler ("+ residence.uniqueMember.first() +")")
BrieLogging.get().debug(type(inst))
#end for
# user.ldap_bind.disconnect()

View File

@ -7,6 +7,7 @@ from brie.config import ldap_config
from brie.config import groups_enum
from brie.lib.ldap_helper import *
from brie.lib.aurore_helper import *
from brie.lib.log_helper import BrieLogging
from brie.lib.plugins import *
from brie.model.ldap import *
@ -59,9 +60,9 @@ class TreasuryController(AuthenticatedBaseController):
dn_prefix = "cn=" + pending_payment.cn.first() + ",cn=" + str(year) + ",cn=cotisations,"
print dn_prefix
BrieLogging.get().debug(dn_prefix)
member_dn = pending_payment.dn[len(dn_prefix):]
print member_dn
BrieLogging.get().debug(member_dn)
member = Member.get_by_dn(self.user, member_dn)
amount_paid = int(pending_payment.get("x-amountPaid").first())

View File

@ -1,5 +1,6 @@
from brie.config import ldap_config
from brie.model.ldap import *
from brie.lib.log_helper import BrieLogging
import datetime
import smtplib
@ -73,7 +74,7 @@ class CotisationComputes:
if paid_months == []:
return next_months_available
print next_months_available
BrieLogging.get().debug(next_months_available)
available_months = [
month
for month in next_months_available
@ -98,8 +99,8 @@ class CotisationComputes:
def price_to_pay(year_price, month_price, already_paid, number_months_to_pay):
months_price = number_months_to_pay * month_price
print "already paid : " + str(already_paid)
print "months price : " + str(months_price)
BrieLogging.get().debug("already paid : " + str(already_paid))
BrieLogging.get().debug("months price : " + str(months_price))
if already_paid + months_price > year_price:
months_price = max(0, year_price - already_paid)
@ -332,7 +333,7 @@ class CotisationComputes:
elif CotisationComputes.is_no_cotisation(member.dn, user_session, residence_dn, cotisations):
no_cotisation_members.append(member)
else:
print "DEBUG : member with weird status !"
BrieLogging.get().warn("aurore_helper:336 member with weird status !")
#end if
#end for
@ -358,7 +359,7 @@ class CotisationComputes:
#end if
#end for
print str(datetime.datetime.now()) + "members_status_from_list_cotisations:" + str(len(members_dict))
BrieLogging.get().debug(str(datetime.datetime.now()) + "members_status_from_list_cotisations:" + str(len(members_dict)))
old_members = []
cotisation_paid_members = []
@ -389,7 +390,7 @@ class CotisationComputes:
elif CotisationComputes.is_no_cotisation(member_dn, user_session, residence_dn, cotisations, anniversary, False):
no_cotisation_members.append(member_dn)
else:
print "DEBUG : member with weird status !"
BrieLogging.get().debug("aurore_helper:393 : member with weird status !")
#end if
#end for

View File

@ -3,6 +3,7 @@ import ldap
#import ldap.modlist as modlist
from brie.config import ldap_config
from brie.lib.log_helper import BrieLogging
from brie.model.ldap import Groupes
@ -321,11 +322,11 @@ class Ldap(object):
)
for ldap_attribute in ldap_attributes:
print "name : " + ldap_attribute.name
print "values : " + str(ldap_attribute.values)
print "deletions : " + str(ldap_attribute._deletions)
print "additions : " + str(ldap_attribute._additions)
print "modified : " + str(ldap_attribute._modified)
BrieLogging.get().debug("name : " + ldap_attribute.name)
BrieLogging.get().debug("values : " + str(ldap_attribute.values))
BrieLogging.get().debug("deletions : " + str(ldap_attribute._deletions))
BrieLogging.get().debug("additions : " + str(ldap_attribute._additions))
BrieLogging.get().debug("modified : " + str(ldap_attribute._modified))
if ldap_attribute._deletions != []:
str_values = [str(value) for value in ldap_attribute._deletions]
@ -348,8 +349,8 @@ class Ldap(object):
#end for
print "dn : " + ldap_entry.dn
print "modlist : " + str(modlist)
BrieLogging.get().debug("dn : " + ldap_entry.dn)
BrieLogging.get().debug("modlist : " + str(modlist))
if modlist != []:
self.__connection.modify_s(ldap_entry.dn, modlist)

View File

@ -0,0 +1,39 @@
#coding: utf-8
import logging
class BrieLogging:
logger = None
@staticmethod
def initializeLog():
# create logger with 'spam_application'
BrieLogging.logger = logging.getLogger('Brie')
BrieLogging.logger.setLevel(logging.DEBUG)
# create file handler which logs even debug messages
fh1 = logging.FileHandler('brie.log')
fh1.setLevel(logging.INFO)
# create file handler which logs even debug messages
fh2 = logging.FileHandler('brie_debug.log')
fh2.setLevel(logging.DEBUG)
# create console handler with a higher log level
#ch = logging.StreamHandler()
#ch.setLevel(logging.ERROR)
# create formatter and add it to the handlers
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
fh1.setFormatter(formatter)
fh2.setFormatter(formatter)
# add the handlers to the logger
BrieLogging.logger.addHandler(fh1)
BrieLogging.logger.addHandler(fh2)
#end def
@staticmethod
def get():
if BrieLogging.logger is None:
BrieLogging.initializeLog()
#end if
return BrieLogging.logger
#end def
#end class