Wordpress plugindevelopment:is_user_logged_in返回false

I'm developing a plugin that'll manage a user log in. In my custom log in form, when credentials are submitted I run this code:

if( isset( $_POST['login'] ) ){

    $login = wp_signon( array(
        'user_login' => $_POST['username'],
        'user_password' => $_POST['password'],
        'remember' => 'true'
    ), true);

    if( is_wp_error( $login ) ){
        echo $login->get_error_message();
    } else {

        $username = $_POST['username'];

        wp_set_current_user( $login->ID, $_POST['username'] );
        wp_set_auth_cookie( $login->ID );
        do_action( 'wp_login', $username );
    }//else

}//if


if( is_user_logged_in() ){ // is_user_logged_in()
    ?><a id="wp-submit" href="<?php echo esc_url( add_query_arg( array( 'ecofriends_logout' => true) ) ); ?>" title="Logout">Logout</a><?php


} else { 
    ecofriends_login_form(); 
}//else

So when the credential are submitted it logs in. If credentials aren't submitted check if the user is logged in to show a logout link else the login form.

The important fact is that here is_user_logged_in() works fine.

In the function.php file I created a function that manage the logout:

function logout(){
if( is_user_logged_in() ){
    wp_logout();
}//if
}//ecofriends_logout

but when I call it is_user_logged_in() always return false even if the user has just logged in.

P.S. I'm working on localhost and the login form is called in a page using a shortcode.

Thank you

Ok, from the comments I think this is what's happening. Your plugin login.php file is invoked on every request, which you said calls the logout() function, ergo logging user out every time.

You need to invoke your logout() function on user triggered action, like clicking on a log out button or in certain conditions you impose.